Part Number Hot Search : 
ANSR2N7 HA178M06 BPC25 06006 CF5760DA 74LX1G32 2SC734 LTC5836P
Product Description
Full Text Search
 

To Download TEMICSEMICONDUCTORS-TSC80C51XXX-40CC Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
  features ? high performance, low power avr ? 8-bit microcontroller ? advanced risc architecture ? 125 powerful instructions ? most single clock cycle execution ? 32 x 8 general purpose working registers ? fully static operation ? up to 16 mips throughput at 16 mhz ? non-volatile program and data memories ? 8k/16k/32k bytes of in-system self-programmable flash ? 512/512/1024 eeprom ? 512/512/1024 internal sram ? write/erase cycles: 10,000 flash/ 100,000 eeprom ? data retention: 20 years at 85 ? c/ 100 years at 25 ? c (1) ? optional boot code section with independent lock bits in-system programming by on-chip boot program hardware-activated after reset true read-while-write operation ? programming lock for software security ? usb 2.0 full-speed device module with interrupt on transfer completion ? complies fully with universal serial bus specification rev 2.0 ? 48 mhz pll for full-speed bus operation : data transfer rates at 12 mbit/s ? fully independant 176 bytes usb dpram for endpoint memory allocation ? endpoint 0 for control transfers: from 8 up to 64-bytes ? 4 programmable endpoints: in or out directions bulk, interrupt and isochronoustransfers programmable maximum packet size from 8 to 64 bytes programmable single or double buffer ? suspend/resume interrupts ? microcontroller reset on usb bus reset without detach ? usb bus disconnection on microcontroller request ? peripheral features ? one 8-bit timer/counters with separate prescaler and compare mode (two 8-bit pwm channels) ? one 16-bit timer/counter with separate prescaler, compare and capture mode (three 8-bit pwm channels) ? usart with spi master only mode and hardware flow control (rts/cts) ? master/slave spi serial interface ? programmable watchdog timer with separate on-chip oscillator ? on-chip analog comparator ? interrupt and wake-up on pin change ? on chip debug interface (debugwire) ? special microcontroller features ? power-on reset and programmable brown-out detection ? internal calibrated oscillator ? external and internal interrupt sources ? five sleep modes: idle, power-save, power-down, standby, and extended standby ? i/o and packages ? 22 programmable i/o lines ? qfn32 (5x5mm) / tqfp32 packages ? operating voltages ? 2.7 - 5.5v ? operating temperature ? industrial (-40c to +85c) ? maximum frequency ? 8 mhz at 2.7v - industrial range ? 16 mhz at 4.5v - industrial range note: 1. see ?data retention? on page 6 for details. 8-bit microcontroller with 8/16/32k bytes of isp flash and usb controller atmega8u2 atmega16u2 atmega32u2 7799e?avr?09/2012
2 7799e?avr?09/2012 atmega8u2/16u2/32u2 1. pin configurations figure 1-1. pinout note: the large center pad underneath the qfn package should be soldered to ground on the board to ensure good mechanical stability. 1.1 disclaimer typical values contained in this datasheet are based on simulations and characterization of other avr microcontrollers manufactured on the same process technology. min and max values will be available after the device is characterized. uvcc qfn32 (pcint11 / ain2 ) pc2 (oc.0b / int0) pd0 vcc xtal1 (int5/ ain3) pd4 (txd1 / int3) pd3 (xck / ain4 / pcint12) pd5 pb3 (pdo / miso / pcint3) gnd (pc0) xtal2 ugnd pb4 (t1 / pcint4) 28 27 26 1 2 3 4 5 6 7 24 23 22 21 20 19 18 12 11 10 9131415 (ain0 / int1) pd1 8 16 17 pb6 (pcint6) d- d+ 25 29 30 31 32 pb7 (pcint7 / oc.0a / oc.1c) pb5 (pcint5) pc7 (int4 / icp1 / clko) pc6 (oc.1a / pcint8) reset (pc1 / dw) pc5 ( pcint9/ oc.1b) pc4 (pcint10) ucap (rxd1 / ain1 / int2) pd2 ( r ts / ain5 / int6) pd6 ( cts / hwb / ain6 / t0 / int7) pd7 ( ss / pcint0) pb0 (sclk / pcint1) pb1 (pdi / mosi / pcint2) pb2 avcc uvcc tqfp32 (pcint11 /ain2 ) pc2 (oc.0b / int0) pd0 vcc xtal1 (int5/ ain3) pd4 (txd1 / int3) pd3 (xck ain4 / pcint12) pd5 pb3 (pdo / miso / pcint3) gnd (pc0) xtal2 ugnd pb4 (t1 / pcint4) 28 27 26 1 2 3 4 5 6 7 24 23 22 21 20 19 18 12 11 10 9131415 (ain0 / int1) pd1 8 16 17 pb6 (pcint6) d- d+ 25 29 30 31 32 pb7 (pcint7 / oc.0a / oc.1c) pb5 (pcint5) pc7 (int4 / icp1 / clko) pc6 (oc.1a / pcint8) reset (pc1 / dw) pc5 ( pcint9/ oc.1b) pc4 (pcint10) ucap (rxd1 / ain1 / int2) pd2 ( r ts / ain5 / int6) pd6 / hwb / ain6 / t0 / int7) pd7 ( ss / pcint0) pb0 (sclk / pcint1) pb1 (pdi / mosi / pcint2) pb2 avcc
3 7799e?avr?09/2012 atmega8u2/16u2/32u2 2. overview the atmega8u2/16u2/32u2 is a low-power cmos 8-bit microc ontroller based on the avr enhanced risc architecture. by executing powerful instructions in a single clock cycle, the atmega8u2/16u2/32u2 achieves throughputs approaching 1 mips per mhz allowing the system designer to optimize power consumption versus processing speed. 2.1 block diagram figure 2-1. block diagram the avr core combines a rich instruction set with 32 general purpose working registers. all the 32 registers are directly connected to the arithmetic logic unit (alu), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. the resulting program counter stack pointer program flash mcu control register sram general purpose registers instruction register timer/ counters instruction decoder data dir. reg. port c data register port c interrupt unit eeprom usart1 status register z y x alu portc drivers portd drivers portb drivers pc7 - pc0 pd7 - pd0 reset vcc gnd xtal1 xtal2 control lines analog comparator pb7 - pb0 d+/sck d-/sdata internal oscillator watchdog timer 8-bit da ta bus usb ps/2 timing and control oscillator calib. osc data dir. reg. port b data register port b on-chip debug debug-wire programming logic data dir. reg. port d data register port d por - bod reset pll + - spi on-chip 3.3v regulator uvcc ucap 1uf
4 7799e?avr?09/2012 atmega8u2/16u2/32u2 architecture is more code efficient while achieving throughputs up to ten times faster than con- ventional cisc microcontrollers. the atmega8u2/16u2/32u2 provides the following features: 8k/16k/32k bytes of in-system programmable flash with read-while-write capabilities, 512/512/1024 bytes eeprom, 512/512/1024 sram, 22 general purpo se i/o lines, 32 general pur pose working registers, two flexible timer/counters with compare modes and pwm, one usart, a programmable watch- dog timer with internal oscillator, an spi serial port, debugwire interface, also used for accessing the on-chip debug system and programming and five software selectable power sav- ing modes. the idle mode stops the cpu while allowing the sram, time r/counters, spi port, and interrupt system to continue functioning. the power-down mode saves the register contents but freezes the oscillator, disabling all other chip functions until the next interrupt or hardware reset. in standby mode, the crystal/resonator oscillator is running while the rest of the device is sleeping. this allows very fast start-up combined with low power consumption. in extended standby mode, the main oscillator continues to run. the device is manufactured using atmel?s high-density nonvolatile memory technology. the on- chip isp flash allows the program memory to be reprogrammed in-system through an spi serial interface, by a conventional nonvolatile memory programmer, or by an on-chip boot program running on the avr core. the boot program can use any interface to download the application program in the application flash memory. software in the boot flash section will continue to run while the application flash section is updated, providing true read-while-write operation. by combining an 8-bit risc cpu with in-system self-programmable flash on a monolithic chip, the atmel atmega8u2/16u2/32u2 is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications. the atmega8u2/16u2/32u2 are supported with a full suite of program and system develop- ment tools including: c compilers, macro assemblers, program debugger/simulators, in-circuit emulators, and evaluation kits. 2.2 pin descriptions 2.2.1 vcc digital supply voltage. 2.2.2 gnd ground. 2.2.3 avcc avcc is the supply voltage pin (input) for all analog features (analog comparator, pll). it should be externally connected to vcc through a low-pass filter. 2.2.4 port b (pb7..pb0) port b is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port b output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port b pins that are externally pulled low will source current if the pull-up resistors are activated. the port b pins are tri-stated when a reset condition becomes active, even if the clock is not running. port b also serves the functions of various special features of the atmega8u2/16u2/32u2 as listed on page 74 .
5 7799e?avr?09/2012 atmega8u2/16u2/32u2 2.2.5 port c (pc7..pc0) port c is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port c output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port c pins that are extern ally pulled low will source current if the pull-up resistors are activated. the port c pins are tri-stated when a reset condition becomes active, even if the clock is not running. port c also serves the functions of various special features of the atmega8u2/16u2/32u2 as listed on page 77 . 2.2.6 port d (pd7..pd0) port d serves as analog inputs to the analog comparator. port d also serves as an 8-bit bi-directional i/o port, if the analog comparator is not used (con- cerns pd2/pd1 pins). port pins can provide internal pull-up resistors (selected for each bit). the port d output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port d pins that are extern ally pulled low will source current if the pull-up resistors are activated. the port d pins are tri-stated when a reset condition becomes active, even if the clock is not running. 2.2.7 d- usb full speed negative data upstream port 2.2.8 d+ usb full speed positive data upstream port 2.2.9 ugnd usb ground. 2.2.10 uvcc usb pads internal regulator input supply voltage. 2.2.11 ucap usb pads internal regulator output supply voltage. should be connected to an external capac- itor (1 f). 2.2.12 reset/pc1/dw reset input. a low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not running. the minimum pulse length is given in ?system control and reset? on page 47 . shorter pulses are not guaranteed to generate a reset. this pin alternatively serves as debugwire channel or as generic i/o. the configuration depends on the fuses rst- disbl and dwen. 2.2.13 xtal1 input to the inverting oscillator amplifier and input to the internal clock operating circuit. 2.2.14 xtal2/pc0 output from the inverting oscillator amplifier if enabled by fuse. also serves as a generic i/o.
6 7799e?avr?09/2012 atmega8u2/16u2/32u2 3. resources a comprehensive set of development tools, application notes and datasheets are available for download on http://www.atmel.com/avr. 4. code examples this documentation contains simple code examples that briefly show how to use various parts of the device. be aware that not all c compiler vendors include bit definitions in the header files and interrupt handling in c is compiler dependent. please confirm with the c compiler documen- tation for more details. these code examples assume that the part specif ic header file is includ ed before compilation. for i/o registers located in extended i/o map, "in", "out", "sbis", "sbic", "cbi", and "sbi" instructions must be replaced with instructions that allow access to extended i/o. typically "lds" and "sts" combined with "sbrs", "sbrc", "sbr", and "cbr". 5. data retention reliability qualification results show that the projected data retention failure rate is much less than 1 ppm over 20 years at 85c or 100 years at 25c.
7 7799d?avr?11/10 atmega8u2/16u2/32u2 6. avr cpu core 6.1 introduction this section discusses the avr core architecture in general. the main function of the cpu core is to ensure correct program execution. the cpu must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts. 6.2 architectural overview figure 6-1. block diagram of the avr architecture in order to maximize performance and parallelism, the avr uses a harvard architecture ? with separate memories and buses for program and data. instructions in the program memory are executed with a single level pipelining. while one instruction is being executed, the next instruc- tion is pre-fetched from the program memory. this concept enables instructions to be executed in every clock cycle. the program memory is in-system reprogrammable flash memory. flash program memory instruction register instruction decoder program counter control lines 32 x 8 general purpose registrers alu status and control i/o lines eeprom data bus 8-bit data sram direct addressing indirect addressing interrupt unit spi unit watchdog timer analog comparator i/o module 2 i/o module1 i/o module n
8 7799d?avr?11/10 atmega8u2/16u2/32u2 the fast-access register file contains 32 x 8-bit general purpose working registers with a single clock cycle access time. this allows single-cycle arithmetic logic unit (alu) operation. in a typ- ical alu operation, two operands are output from the register file, the operation is executed, and the result is stored back in the register file ? in one clock cycle. six of the 32 registers can be used as three 16-bit indirect address register pointers for data space addressing ? enabling efficient address calculations. one of these address pointers can also be used as an address pointer for look up tables in flash program memory. these added function registers are the 16-bit x-, y-, and z-register, described later in this section. the alu supports arithmetic and logic operations between registers or between a constant and a register. single register operations can also be executed in the alu. after an arithmetic opera- tion, the status register is updated to reflect information about the result of the operation. program flow is provided by conditional and unconditional jump and call instructions, able to directly address the whole address space. most avr instructions have a single 16-bit word for- mat. every program memory address contains a 16- or 32-bit instruction. program flash memory space is divided in two sections, the boot program section and the application program section. both sections have dedicated lock bits for write and read/write protection. the spm instruction that writes into the application flash memory section must reside in the boot program section. during interrupts and subroutine calls, the return address program counter (pc) is stored on the stack. the stack is effectively allocated in the general data sram, and consequently the stack size is only limited by the total sram size and the usage of the sram. all user programs must initialize the sp in the reset routine (before subroutines or interrupts are executed). the stack pointer (sp) is read/write accessible in the i/o space. the data sram can easily be accessed through the five different addressing modes supported in the avr architecture. the memory spaces in the avr architecture are all linear and regular memory maps. a flexible interrupt module has its control registers in the i/o space with an additional global interrupt enable bit in the status register. all in terrupts have a separate interrupt vector in the interrupt vector table. the interrupts have priority in accordance with their interrupt vector posi- tion. the lower the interrupt vector address, the higher the priority. the i/o memory space contains 64 addresses for cpu peripheral functions as control regis- ters, spi, and other i/o functions. the i/o memory can be accessed directly, or as the data space locations following those of the register file, 0x20 - 0x5f. in addition, the atmega8u2/16u2/32u2 has extended i/o space from 0x60 - 0xff in sram where only the st/sts/std and ld/lds/ldd instructions can be used. 6.3 alu ? arithmetic logic unit the high-performance avr alu operates in direct connection with all the 32 general purpose working registers. within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. the alu operations are divided into three main categories ? arithmetic, logical, and bit-functions. see the ?instruction set? sec- tion for a detailed description. 6.4 status register the status register contains information about the result of the most recently executed arithme- tic instruction. this information can be used for altering program flow in order to perform
9 7799d?avr?11/10 atmega8u2/16u2/32u2 conditional operations. note that the status register is updated after all alu operations, as specified in the instruction set reference. this will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. the status register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. this must be handled by software. 6.4.1 sreg ? status register ? bit 7 ? i: global interrupt enable the global interrupt enable bit must be set for the interrupts to be enabled. the individual inter- rupt enable control is then performed in separate control registers. if the global interrupt enable register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. the i-bit is cleared by hardware after an interrupt has occurred, and is set by the reti instruction to enable subsequent interrupts. the i-bit can also be set and cleared by the application with the sei and cli instructions, as described in the instruction set reference. ? bit 6 ? t: bit copy storage the bit copy instructions bld (bit load) and bst (bit store) use the t-bit as source or desti- nation for the operated bit. a bit from a register in the register file can be copied into t by the bst instruction, and a bit in t can be copied into a bit in a register in the register file by the bld instruction. ? bit 5 ? h: half carry flag the half carry flag h indicates a half carry in some arithmetic operations. half carry is useful in bcd arithmetic. see the ?instruction set description? for detailed information. ? bit 4 ? s: sign bit, s = n ?? v the s-bit is always an exclusive or between the negative flag n and the two?s complement overflow flag v. see the ?instruction set description? for detailed information. ? bit 3 ? v: two?s complement overflow flag the two?s complement overflow flag v supports two?s complement arithmetics. see the ?instruction set description? for detailed information. ? bit 2 ? n: negative flag the negative flag n indicates a negative result in an arithmetic or logic operation. see the ?instruction set description? for detailed information. ? bit 1 ? z: zero flag the zero flag z indicates a zero result in an arithmetic or logic operation. see the ?instruction set description? for detailed information. bit 76543210 0x3f (0x5f) i t h s v n z c sreg read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
10 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 0 ? c: carry flag the carry flag c indicates a carry in an arithmetic or logic operation. see the ?instruction set description? for detailed information. 6.5 general purpose register file the register file is optimized for the avr enhanced risc instruction set. in order to achieve the required performance and flexibility, the following input/output schemes are supported by the register file: ? one 8-bit output operand and one 8-bit result input ? two 8-bit output operands and one 8-bit result input ? two 8-bit output operands and one 16-bit result input ? one 16-bit output operand and one 16-bit result input figure 6-2 shows the structure of the 32 general purpose working registers in the cpu. figure 6-2. avr cpu general purpose working registers most of the instructions operating on the register file have direct access to all registers, and most of them are single cycle instructions. as shown in figure 6-2 , each register is also assigned a data memory address, mapping them directly into the first 32 locations of the user data space. although not being physically imple- mented as sram locations, this memory organizat ion provides great flexibility in access of the registers, as the x-, y- and z-pointer registers can be set to index any register in the file. 6.5.1 the x-register, y-register, and z-register the registers r26..r31 have some added functions to their general purpose usage. these reg- isters are 16-bit address pointers for indirect addressing of the data space. the three indirect address registers x, y, and z are defined as described in figure 6-3 . 7 0 addr. r0 0x00 r1 0x01 r2 0x02 ? r13 0x0d general r14 0x0e purpose r15 0x0f working r16 0x10 registers r17 0x11 ? r26 0x1a x-register low byte r27 0x1b x-register high byte r28 0x1c y-register low byte r29 0x1d y-register high byte r30 0x1e z-register low byte r31 0x1f z-register high byte
11 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 6-3. the x-, y-, and z-registers in the different addressing modes these address registers have functions as fixed displacement, automatic increment, and automatic decrement (see the instruction set reference for details). 6.6 stack pointer the stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. note that the stack is implemented as growing from higher to lower memory locations. the stack pointer register always points to the top of the stack. the stack pointer points to the data sram stack area where the subroutine and interrupt stacks are located. a stack push command will decrease the stack pointer. the stack in the data sram must be defined by the program before any subroutine calls are executed or interrupts are enabled. initial stack pointer value equals the last address of the internal sram and the stack pointer must be set to point above start of the sram, see figure 7-2 on page 18 . see table 6-1 for stack pointer details. the avr stack pointer is implemented as two 8-bit registers in the i/o space. the number of bits actually used is implementation dependent. note that the data space in some implementa- tions of the avr architecture is so small that only spl is needed. in this case, the sph register will not be present. 15 xh xl 0 x-register 7 0 7 0 r27 (0x1b) r26 (0x1a) 15 yh yl 0 y-register 7 0 7 0 r29 (0x1d) r28 (0x1c) 15 zh zl 0 z-register 7 0 7 0 r31 (0x1f) r30 (0x1e) table 6-1. stack pointer instructions instruction stack pointer description push decremented by 1 data is pushed onto the stack call icall rcall decremented by 2 return address is pushed onto the stack with a subroutine call or interrupt pop incremented by 1 data is popped from the stack ret reti incremented by 2 return address is popped from the stack with return from subroutine or return from interrupt
12 7799d?avr?11/10 atmega8u2/16u2/32u2 6.6.1 sph and spl ? stack pointer high and low register 6.7 instruction execution timing this section describes the general access timing concepts for instruction execution. the avr cpu is driven by the cpu clock clk cpu , directly generated from the selected clock source for the chip. no internal clock division is used. figure 6-4 shows the parallel instruction fetches and instruction executions enabled by the har- vard architecture and the fast-access register file concept. this is the basic pipelining concept to obtain up to 1 mips per mhz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. figure 6-4. the parallel instruction fetches and instruction executions figure 6-5 shows the internal timing concept for the register file. in a single clock cycle an alu operation using two register operands is executed , and the result is stored back to the destina- tion register. figure 6-5. single cycle alu operation bit 15 14 13 12 11 10 9 8 0x3e (0x5e) sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 sph 0x3d (0x5d) sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 spl 76543210 read/write r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 1 0 0 0 0 0 11111111 clk 1st instruction fetch 1st instruction execute 2nd instruction fetch 2nd instruction execute 3rd instruction fetch 3rd instruction execute 4th instruction fetch t1 t2 t3 t4 cpu total execution time register operands fetch alu operation execute result write back t1 t2 t3 t4 clk cpu
13 7799d?avr?11/10 atmega8u2/16u2/32u2 6.8 reset and interrupt handling the avr provides several different interrupt sou rces. these interrupts and the separate reset vector each have a separate program vector in the program memory space. all interrupts are assigned individual enable bits which must be written logic one together with the global interrupt enable bit in the status register in order to enable the interrupt. depending on the program counter value, interrupts may be automaticall y disabled when boot lock bits blb02 or blb12 are programmed. this feature improves software security. see the section ?memory program- ming? on page 246 for details. the lowest addresses in the program memory space are by default defined as the reset and interrupt vectors. the complete list of vectors is shown in ?interrupts? on page 64 . the list also determines the priority levels of the different interrupts. the lower the address the higher is the priority level. reset has the highest priority, and next is int0 ? the external interrupt request 0. the interrupt vectors can be moved to the start of the boot flash section by setting the ivsel bit in the mcu control register (mcucr). refer to ?interrupts? on page 64 for more information. the reset vector can also be moved to the start of the boot flash section by programming the bootrst fuse, see ?memory programming? on page 246 . when an interrupt occurs, the global interrupt en able i-bit is cleared an d all interrupts are dis- abled. the user software can write logic one to the i-bit to enable nested interrupts. all enabled interrupts can then interrupt the current interrupt routine. the i-bit is automatically set when a return from interrupt instruction ? reti ? is executed. there are basically two types of interrupts. the first type is triggered by an event that sets the interrupt flag. for these interrupts, the program counter is vectored to the actual interrupt vec- tor in order to execute the interrupt handling routine, and hardware clears the corresponding interrupt flag. interrupt flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. if an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the interrupt flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. similarly, if one or more interrupt conditions occur while the global interrupt enable bit is cleared, the corresponding interrupt flag(s) will be set and remembered until the global interrupt enable bit is set, and will then be executed by order of priority. the second type of interrupts will trigger as long as the interrupt condition is present. these interrupts do not necessarily have interrupt flags. if the interrupt condition disappears before the interrupt is enabled, the interrupt will not be triggered. when the avr exits from an interrupt, it will always return to the main program and execute one more instruction before any pending interrupt is served. note that the status register is not automatically stored when entering an interrupt routine, nor restored when returning from an interrupt routine. this must be handled by software. when using the cli instruction to disable interrupts, the interrupts will be immediately disabled. no interrupt will be executed after the cli instruction, even if it occurs simultaneously with the
14 7799d?avr?11/10 atmega8u2/16u2/32u2 cli instruction. the following example shows how this can be used to avoid interrupts during the timed eeprom write sequence.. when using the sei instruction to enable interrupts, the instruction following sei will be exe- cuted before any pending interrupts, as shown in this example. assembly code example in r16, sreg ; store sreg value cli ; disable interrupts during timed sequence sbi eecr, eempe ; start eeprom write sbi eecr, eepe out sreg, r16 ; restore sreg value (i-bit) c code example char csreg; csreg = sreg; /* store sreg value */ /* disable interrupts during timed sequence */ __disable_interrupt(); eecr |= (1< 15 7799d?avr?11/10 atmega8u2/16u2/32u2 6.8.1 interrupt response time the interrupt execution response for all the enabled avr interrupts is five clock cycles minimum. after five clock cycles the program vector address for the actual interrupt handling routine is exe- cuted. during these five clock cycle period, the program counter is pushed onto the stack. the vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. if an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed before the interrupt is served. if an interrupt occurs when the mcu is in sleep mode, the interrupt exe- cution response time is increased by five clock cycles. this increase comes in addition to the start-up time from the selected sleep mode. a return from an interrupt handling routine takes five clock cycles. during these five clock cycles, the program counter (three bytes) is popped back from the stack, the stack pointer is incre- mented by three, and the i-bit in sreg is set. assembly code example sei ; set global interrupt enable sleep ; enter sleep, waiting for interrupt ; note: will enter sleep before any pending ; interrupt(s) c code example __enable_interrupt(); /* set global interrupt enable */ __sleep(); /* enter sleep, waiting for interrupt */ /* note: will enter sleep before any pending interrupt(s) */
16 7799d?avr?11/10 atmega8u2/16u2/32u2 7. avr memories this section describes the different memories in the atmega8u2/16u2/32u2. the avr archi- tecture has two main memory spaces, the data memory and the program memory space. in addition, the atmega8u2/16u2/32u2 features an eeprom memory for data storage. all three memory spaces are linear and regular. 7.1 in-system reprogrammable flash program memory the atmega8u2/16u2/32u2 contains 8k/16k/32k bytes on-chip in-system reprogrammable flash memory for program storage. since all avr instructions are 16 or 32 bits wide, the flash is organized as 4k x 16, 8k x 16. for software security, the flash program memory space is divided into two sections, boot program section and application program section. the flash memory has an endurance of at least 100,000 write/erase cycles. the atmega8u2/16u2/32u2 program counter (pc) is 16 bits wide, thus addressing the 8k/16k/32k program memory locations. the operation of boot program section and associated boot lock bits for software protection are described in detail in ?memory programming? on page 246 . ?memory programming? on page 246 contains a detailed description on flash data serial downloading using the spi pins or the debugwire interface. constant tables can be allocated within the entire program memory address space (see the lpm ? load program memory instruction descriptio n and elpm - extended load program memory instruction description). timing diagrams for instruction fetch and execution are presented in ?instruction execution tim- ing? on page 12 .
17 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 7-1. program memory map 7.2 sram data memory figure 7-2 shows how the atmega8u2/16u2/32u2 sram memory is organized. the atmega8u2/16u2/32u2 is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in the opcode for the in and out instructions. for the extended i/o space from $060 - $0ff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. the first 768 data memory locations address the register file, the i/o memory, extended i/o memory, and the internal data sram. the first 32 locations address th e register file, the next 64 location the standard i/o memory, then 160 locations of extended i/o memory, and the 512 locations of internal data sram.the five different addressing modes for the data memory cover: direct, indirect with displacement, indirect, indirect with pre-decrement, and indirect with post- increment. in the register file, registers r26 to r31 feature the indirect addressing pointer registers. the direct addressing reaches the entire data space. the indirect with displacement mode reaches 63 address locations from the base address given by the y- or z-register. when using register indirect addressing modes with automatic pre-decrement and post-incre- ment, the address registers x, y, and z are decremented or incremented. 0x00000 0x1fff (8kbytes) 0x3fff (16kbytes) program memory application flash section boot flash section 0x7fff (32kbytes)
18 7799d?avr?11/10 atmega8u2/16u2/32u2 the 32 general purpose working registers, 64 i/o registers, and the 512/512/1024bytes of inter- nal data sram in the atmega8u2/16u2/32u2 are all accessible through all these addressing modes. the register file is described in ?general purpose register file? on page 10 . figure 7-2. data memory map 7.2.1 data memory access times this section describes the general access timing concepts for internal memory access. the internal data sram access is performed in two clk cpu cycles as described in figure 7-3 . figure 7-3. on-chip data sram access cycles 7.3 eeprom data memory the atmega8u2/16u2/32u2 contains 512/512/1024 bytes of data eeprom memory. it is orga- nized as a separate data space, in which single bytes can be read and written. the eeprom has an endurance of at least 100,000 write/erase cycles. the access between the eeprom and the cpu is described in the following, specifying the eeprom address registers, the eeprom data register, and the eeprom control register. 32 registers 64 i/o registers internal sram (512/512/1024 x 8) $0000 - $001f $0020 - $005f $2ff/$2ff/$4ff (8u2/16u2/32u2) $0060 - $00ff data memory 160 ext i/o reg. $0100 clk wr rd data data address address valid t1 t2 t3 compute address read write cpu memory access instruction next instruction
19 7799d?avr?11/10 atmega8u2/16u2/32u2 for a detailed description of spi, debugwire and parallel data download ing to the eeprom, see page 259 , page 244 , and page 250 respectively. 7.3.1 eeprom read/write access the eeprom access registers are accessible in the i/o space. the write access time for the eeprom is given in table 7-2 on page 22 . a self-timing function, however, lets the user software detect when the next byte can be written. if the user code con- tains instructions that write the eeprom, some precautions must be taken. in heavily filtered power supplies, v cc is likely to rise or fall slowly on power-up/down. this causes the device for some period of time to run at a voltage lower than specified as minimum for the clock frequency used. see ?preventing eeprom corruption? on page 19. for details on how to avoid problems in these situations. in order to prevent unintentional eeprom writes, a specific write procedure must be followed. refer to the description of the eeprom control register for details on this. when the eeprom is read, the cpu is halted for four clock cycles before the next instruction is executed. when the eeprom is written, the cpu is halted for two clock cycles before the next instruction is executed. 7.3.2 preventing eeprom corruption during periods of low v cc, the eeprom data can be corrupted because the supply voltage is too low for the cpu and the eeprom to operate properly. these issues are the same as for board level systems using eeprom, and the same design solutions should be applied. an eeprom data corruption can be caused by two situations when the voltage is too low. first, a regular write sequence to the eeprom requires a minimum voltage to operate correctly. sec- ondly, the cpu itself can execute instructions incorrectly, if the supply voltage is too low. eeprom data corruption can easily be avoided by following this design recommendation: keep the avr reset active (low) during periods of insufficient power supply voltage. this can be done by enabling the internal brown-out detector (bod). if the detection level of the internal bod does not match the needed detection level, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress, the write operation will be com- pleted provided that the power supply voltage is sufficient. 7.4 i/o memory the i/o space definition of the atmega8u2/16u2/32u2 is shown in ?register summary? on page 288 . all atmega8u2/16u2/32u2 i/os and peripherals are placed in the i/o space. all i/o locations may be accessed by the ld/lds/ldd and st/sts/std instructions, transferring data between the 32 general purpose working registers and the i/o space. i/o registers within the address range 0x00 - 0x1f are directly bit-accessible using the sbi and cbi instructions. in these regis- ters, the value of single bits can be checked by using the sbis and sbic instructions. refer to the instruction set section for more details. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the atmega8u2/16u2/32u2 is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for the
20 7799d?avr?11/10 atmega8u2/16u2/32u2 extended i/o space from 0x60 - 0x1ff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. for compatibility with future devices, reserved bits should be written to zero if accessed. reserved i/o memory addresses should never be written. some of the status flags are cleared by writing a logical one to them. note that, unlike most other avrs, the cbi and sbi instructions will only operate on the specified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions work with reg- isters 0x00 to 0x1f only. the i/o and peripherals control registers are explained in later sections. 7.4.1 general purpose i/o registers the atmega8u2/16u2/32u2 contains three general purpose i/o registers. these registers can be used for storing any information, and they are particularly useful for storing global vari- ables and status flags. general purpose i/o registers within the address range 0x00 - 0x1f are directly bit-accessible using the sbi, cbi, sbis, and sbic instructions. 7.5 register description 7.5.1 eearh and eearl ? the eeprom address register ? bits 15:12 ? res: reserved bits these bits are reserved and will always read as zero. ? bits 11:0 ? eear[8:0]: eeprom address the eeprom address registers ? eearh and eearl specify the eeprom address in the 512 bytes eeprom space. the eeprom data bytes are addressed linearly between 0 and 512. the initial value of eear is undefined. a proper value must be written before the eeprom may be accessed. 7.5.2 eedr ? the eeprom data register ? bits 7:0 ? eedr[7:0]: eeprom data for the eeprom write operation, the eedr register contains the data to be written to the eeprom in the address given by the eear register. for the eeprom read operation, the eedr contains the data read out from the eeprom at the address given by eear. bit 15 14 13 12 11 10 9 8 0x22 (0x42) ? ? ? ? eear11 eear10 eear9 eear8 eearh 0x21 (0x41) eear7 eear6 eear5 eear4 eear3 eear2 eear1 eear0 eearl 76543 210 read/write r r r r r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 x x x x xxxx x x xx bit 76543210 0x20 (0x40) msb lsb eedr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
21 7799d?avr?11/10 atmega8u2/16u2/32u2 7.5.3 eecr ? the eeprom control register ? bits 7:6 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bits 5, 4 ? eepm1 and eepm0: eeprom programming mode bits the eeprom programming mode bit setting defines which programming action that will be trig- gered when writing eepe. it is possible to program data in one atomic operation (erase the old value and program the new value) or to split the erase and write operations in two different operations. the programming times for the different modes are shown in table 7-1 . while eepe is set, any write to eepmn will be ignored. during reset, the eepmn bits will be reset to 0b00 unless the eeprom is busy programming. ? bit 3 ? eerie: eeprom ready interrupt enable writing eerie to one enables the ee prom ready interrupt if the i bit in sreg is set. writing eerie to zero disables the interrupt. the eeprom ready interrupt generates a constant inter- rupt when eepe is cleared. ? bit 2 ? eempe: eeprom master programming enable the eempe bit determines whether setting eepe to one causes the eeprom to be written. when eempe is set, setting eepe within four clock cycles will write data to the eeprom at the selected address if eempe is zero, setting eepe will have no effect. when eempe has been written to one by software, hardware clears the bit to zero after four clock cycles. see the description of the eepe bit for an eeprom write procedure. ? bit 1 ? eepe: eeprom programming enable the eeprom write enable signal eepe is the write strobe to the eeprom. when address and data are correctly set up, the eepe bit must be written to one to write the value into the eeprom. the eempe bit must be written to one before a logical one is written to eepe, other- wise no eeprom write takes place. the following procedure should be followed when writing the eeprom (the order of steps 3 and 4 is not essential): bit 76543210 0x1f (0x3f) ? ? eepm1 eepm0 eerie eempe eepe eere eecr read/write r r r/w r/w r/w r/w r/w r/w initial value 0 0 x x 0 0 x 0 table 7-1. eeprom mode bits eepm1 eepm0 programming time operation 0 0 3.4 ms erase and write in one operation (atomic operation) 0 1 1.8 ms erase only 1 0 1.8 ms write only 1 1 ? reserved for future use
22 7799d?avr?11/10 atmega8u2/16u2/32u2 1. wait until eepe becomes zero. 2. wait until selfprgen in spmcsr becomes zero. 3. write new eeprom address to eear (optional). 4. write new eeprom data to eedr (optional). 5. write a logical one to the eempe bit while writing a zero to eepe in eecr. 6. within four clock cycles after setting eempe, write a logical one to eepe. the eeprom can not be programmed during a cp u write to the flash memory. the software must check that the flash programming is completed before initiating a new eeprom write. step 2 is only relevant if the software contains a boot loader allowing the cpu to program the flash. if the flash is never being updated by the cpu, step 2 can be omitted. see ?memory pro- gramming? on page 246 for details about boot programming. caution: an interrupt between step 5 and step 6 will make the write cycle fail, since the eeprom master write enable will time-out. if an interrupt routine accessing the eeprom is interrupting another eeprom access, the eear or eedr register will be modified, causing the interrupted eeprom access to fail. it is recommended to have the global interrupt flag cleared during all the steps to avoid these problems. when the write access time has elapsed, the eepe bit is cleared by hardware. the user soft- ware can poll this bit and wait for a zero before writing the next byte. when eepe has been set, the cpu is halted for two cycles before the next instruction is executed. ? bit 0 ? eere: eeprom read enable the eeprom read enable signal eere is the read strobe to the eeprom. when the correct address is set up in the eear register, the eere bit must be written to a logic one to trigger the eeprom read. the eeprom read access takes one instruction, and the requested data is available immediately. when the eeprom is read, the cpu is halted for four cycles before the next instruction is executed. the user should poll the eepe bit before starting the read operation. if a write operation is in progress, it is neither possible to read the eeprom, nor to change the eear register. the calibrated oscillator is used to time the eeprom accesses. table 7-2 lists the typical pro- gramming time for eeprom access from the cpu. the following code examples show one assembly and one c function for writing to the eeprom. the examples assume that interrupts are controlled (e.g. by disabling interrupts glob- ally) so that no interrupts will occur during execution of these functions. the examples also assume that no flash boot loader is present in the software. if such code is present, the eeprom write function must also wait for any ongoing spm command to finish. table 7-2. eeprom programming time symbol number of calibrated rc oscillator cycles typ programming time eeprom write (from cpu) 26,368 3.3 ms
23 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. see ?code examples? on page 6. assembly code example (1) eeprom_write: ; wait for completion of previous write sbic eecr,eepe rjmp eeprom_write ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; write data (r16) to data register out eedr,r16 ; write logical one to eempe sbi eecr,eempe ; start eeprom write by setting eepe sbi eecr,eepe ret c code example (1) void eeprom_write( unsigned int uiaddress, unsigned char ucdata) { /* wait for completion of previous write */ while(eecr & (1< 24 7799d?avr?11/10 atmega8u2/16u2/32u2 the next code examples show assembly and c functions for reading the eeprom. the exam- ples assume that interrupts are controlled so that no interrupts will occur during execution of these functions. note: 1. see ?code examples? on page 6. 7.5.4 gpior2 ? general purpose i/o register 2 7.5.5 gpior1 ? general purpose i/o register 1 assembly code example (1) eeprom_read: ; wait for completion of previous write sbic eecr,eepe rjmp eeprom_read ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; start eeprom read by writing eere sbi eecr,eere ; read data from data register in r16,eedr ret c code example (1) unsigned char eeprom_read( unsigned int uiaddress) { /* wait for completion of previous write */ while(eecr & (1< 25 7799d?avr?11/10 atmega8u2/16u2/32u2 7.5.6 gpior0 ? general purpose i/o register 0 bit 76543210 0x1e (0x3e) msb lsb gpior0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
26 7799d?avr?11/10 atmega8u2/16u2/32u2 8. system clock and clock options 8.1 clock systems and their distribution figure 8-1 presents the principal clock systems in the avr and their distribution. all of the clocks need not be active at a given time. in order to reduce power consumption, the clocks to modules not being used can be halted by using different sleep modes, as described in ?power manage- ment and sleep modes? on page 42 . the clock systems are detailed below. figure 8-1. clock distribution 8.1.1 cpu clock ? clk cpu the cpu clock is routed to parts of the system concerned with operation of the avr core. examples of such modules are the general purpose register file, the status register and the data memory holding the stack pointer. halting the cpu clock inhibits the core from performing general operations and calculations. 8.1.2 i/o clock ? clk i/o the i/o clock is used by the majority of the i/o modules, like timer/counters, spi, and usart. the i/o clock is also used by the external interrupt module, but note that some external inter- rupts are detected by asynchronous logic, allowing such interrupts to be detected even if the i/o clock is halted. 8.1.3 flash clock ? clk flash the flash clock controls operation of the flash interface. the flash clock is usually active simul- taneously with the cpu clock. general i/o modules cpu core ram clk i/o avr clock control unit clk cpu flash and eeprom clk flash source clock watchdog timer reset logic clock multiplexer watchdog clock calibrated rc oscillator system clock prescaler watchdog oscillator usb clk usb (48mhz) pll clock prescaler clk pllin (8mhz) usb pll x6 clk xtal (2-16 mhz) crystal oscillator external clock
27 7799d?avr?11/10 atmega8u2/16u2/32u2 8.1.4 usb clock ? clk usb the usb is provided with a dedicated clock domain. this clock is generated with an on-chip pll running at 48 mhz. the pll always multiply its input frequency by 6. thus the pll clock register should be programmed by software to generate a 8 mhz clock on the pll input. 8.2 clock switch in the atmega8u2/16u2/32u2 product, the cloc k multiplexer and the system clock prescaler can be modified by software. 8.2.1 exemple of use the modification can occur when the device enters in usb suspend mode. it then switches from external clock to calibrated rc oscillator in order to reduce consumption. in such a configura- tion, the external clock is disabled. the firmware can use the watchdog timer to be woken-up from power-down in order to check if there is an event on the application. if an event occurs on the application or if the usb controller signals a non-idle state on the usb line (resume for example), the firmware switches the clock multiplexer from the calibrated rc oscillator to the external clock. figure 8-2. example of clock switching with wake-up from usb host usb cpu clock external oscillator rc oscillator ext rc ext non-idle idle (suspend) non-idle 3ms resume 1 1 resume from host watchdog wake-up from power-down
28 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 8-3. example of clock switching with wake-up from device 8.2.2 clock switch algorythm 8.2.2.1 swith from external clock to rc clock if (usb_suspend_detected()) // if (udint.suspi == 1) { usb_ack_suspend(); // udint.suspi = 0; usb_freeze_clock(); // usbcon.frzclk = 1; disable_pll(); // pllcsr.plle = 0; enable_rc_clock(); // clksel0.rce = 1; while (!rc_clock_ready()); // while (clksta.rcon != 1); select_rc_clock(); // clksel0.clks = 0; disable_external_clock(); // clksel0.exte = 0; } 8.2.2.2 switch from rc clock to external clock if (usb_wake_up_detected()) // if (udint.wakeupi == 1) { usb_ack_wake_up(); // udint.wakeupi = 0; enable_external_clock(); // cksel0.exte = 1; while (!external_clock_ready()); // while (clksta.exton != 1); select_external_clock(); // clksel0.clks = 1; enable_pll(); // pllcsr.plle = 1; disable_rc_clock(); // clksel0.rce = 0; while (!pll_ready()); // while (pllcsr.plock != 1); usb_unfreeze_clock(); // usbcon.frzclk = 0; } usb cpu clock external oscillator rc oscillator ext rc ext non-idle idle (suspend) non-idle 3ms upstream-resume 2 2 upstream resume from device watchdog wake-up from power-down
29 7799d?avr?11/10 atmega8u2/16u2/32u2 8.3 clock sources the device has the following clock source options, selectable by flash fuse bits as shown below. the clock from the selected source is input to the avr clock generator, and routed to the appropriate modules. note: 1. for all fuses ?1? means unprogrammed while ?0? means programmed. 8.3.1 default clock source the device is shipped with internal rc oscillator at 8.0 mhz and with the fuse ckdiv8 pro- grammed, resulting in 1.0 mhz system clock. th e startup time is set to maximum and time-out period enabled. (cksel = "0010", sut = "10", ckdiv8 = "0"). the default setting ensures that all users can make their desired clock source setting using any available programming interface. 8.3.2 clock startup sequence any clock source needs a sufficient v cc to start oscillating and a minimum number of oscillating cycles before it can be considered stable. to ensure sufficient v cc , the device issues an internal reset with a time-out delay (t tout ) after the device reset is released by all other reset sources. ?on-chip debug system? on page 45 describes the start conditions for the internal reset. the delay (t tout ) is timed from the watchdog oscillator and the number of cycles in the delay is set by the sutx and ckselx fuse bits. the selectable delays are shown in table 8-2 . the frequency of the watchdog oscillator is voltage dependent as shown in ?typical characteristics? on page 273 . main purpose of the delay is to keep the avr in reset until it is supplied with minimum vcc. the delay will not monitor the actual voltage and it will be required to select a delay longer than the vcc rise time. if this is not possible, an internal or external brown-out detection circuit should be used. a bod circuit will ensure sufficient vcc before it releases the reset, and the time-out delay can be disabled. disabling the time-out delay without utilizing a brown-out detection circuit is not recommended. table 8-1. device clocking options select (1) device clocking option cksel3:0 low power crystal oscillator 1111 - 1000 full swing crystal oscillator 0111 - 0110 reserved 0101 - 0100 reserved 0011 calibrated internal rc oscillator 0010 external clock 0000 reserved 0001 table 8-2. number of watchdog oscillator cycles typ time-out (v cc = 5.0v) typ time-out (v cc = 3.0v) number of cycles 0 ms 0 ms 0 4.1 ms 4.3 ms 512 65 ms 69 ms 8k (8,192)
30 7799d?avr?11/10 atmega8u2/16u2/32u2 the oscillator is required to oscillate for a minimum number of cycles before the clock is consid- ered stable. an internal ripple counter monitors the oscillator output clock, and keeps the internal reset active for a given number of clock cycles. the reset is then released and the device will start to execute. the recommended oscillator start-up time is dependent on the clock type, and varies from 6 cycles for an externally applied clock to 32k cycles for a low frequency crystal. the start-up sequence for the clock includes both the time-out delay and the start-up time when the device starts up from reset. when starting up from power-save or power-down mode, vcc is assumed to be at a sufficient level and only the start-up time is included. 8.4 low power crystal oscillator pins xtal1 and xtal2 are input and output, respectively, of an inverting amplifier which can be configured for use as an on-chip oscillator, as shown in figure 8-4 . either a quartz crystal or a ceramic resonator may be used. this crystal oscillator is a low power oscillator, with reduced voltage swing on the xtal2 out- put. it gives the lowest power consumption, but is not capable of driving other clock inputs, and may be more susceptible to noise in noisy environments. c1 and c2 should always be equal for both crystals and resonators. the optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the environment. some initial guidelines for choosing capacitors for use with crystals are given in table 8-3 . for ceramic resonators, the capacitor values given by the manufacturer should be used. figure 8-4. crystal oscillator connections the low power oscillator can operate in three different modes, each optimized for a specific fre- quency range. the operating mode is selected by the fuses cksel3..1 as shown in table 8-3 . notes: 1. the frequency ranges are preliminary values. actual values are tbd. 2. this option should not be used with crystals, only with ceramic resonators. table 8-3. low power crystal oscillator operating modes (3) frequency range (1) (mhz) cksel3..1 recommended range for capacitors c1 and c2 (pf) 0.4 - 0.9 100 (2) ? 0.9 - 3.0 101 12 - 22 3.0 - 8.0 110 12 - 22 8.0 - 16.0 111 12 - 22 xtal2 xtal1 gnd c2 c1
31 7799d?avr?11/10 atmega8u2/16u2/32u2 3. if 8 mhz frequency exceeds the specification of the device (depends on v cc ), the ckdiv8 fuse can be programmed in order to divide the internal frequency by 8. it must be ensured that the resulting divided clock meets the frequency specification of the device. the cksel0 fuse together with the sut1..0 fuses select the start-up times as shown in table 8-4 . notes: 1. these options should only be used when not operating close to the maximum frequency of the device, and only if frequency stability at start-up is not important for the application. these options are not suitable for crystals. 2. these options are intended for use with ceramic resonators and will ensure frequency stability at start-up. they can also be used with crystals when not operating close to the maximum fre- quency of the device, and if frequency stability at start-up is not important for the application. note: 1. the device is shipped with this option selected. table 8-4. start-up times for the low power crystal oscillator clock selection oscillator source / power conditions start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) cksel0 sut1..0 ceramic resonator, fast rising power 258 ck 14ck + 4.1 ms (1) 000 ceramic resonator, slowly rising power 258 ck 14ck + 65 ms (1) 001 ceramic resonator, bod enabled 1k ck 14ck (2) 010 ceramic resonator, fast rising power 1k ck 14ck + 4.1 ms (2) 011 ceramic resonator, slowly rising power 1k ck 14ck + 65 ms (2) 100 crystal oscillator, bod enabled 16k ck 14ck 1 01 crystal oscillator, fast rising power 16k ck 14ck + 4.1 ms 1 10 crystal oscillator, slowly rising power 16k ck 14ck + 65 ms 1 11 table 8-5. start-up times for the internal calibrated rc oscillator clock selection power conditions start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) sut1..0 bod enabled 6 ck 14ck 00 fast rising power 6 ck 14ck + 4.1 ms 01 slowly rising power 6 ck 14ck + 65 ms (1) 10 reserved 11
32 7799d?avr?11/10 atmega8u2/16u2/32u2 8.5 full swing crystal oscillator pins xtal1 and xtal2 are input and output, respectively, of an inverting amplifier which can be configured for use as an on-chip oscillator, as shown in figure 8-4 . either a quartz crystal or a ceramic resonator may be used. this crystal oscillator is a full swing oscillator, with rail-to-rail swing on the xtal2 output. this is useful for driving other clock inputs and in noisy environments. the current consumption is higher than the ?low power crystal oscillator? on page 30 . note that the full swing crystal oscillator will only operate for v cc = 2.7 - 5.5 volts. c1 and c2 should always be equal for both crystals and resonators. the optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the environment. some initial guidelines for choosing capacitors for use with crystals are given in table 1 . for ceramic resonators, the capacitor values given by the manufacturer should be used.
33 7799d?avr?11/10 atmega8u2/16u2/32u2 notes: 1. these options should only be used when not operating close to the maximum frequency of the device, and only if frequency stability at start-up is not important for the application. these options are not suitable for crystals. they can also be used with crystals when not operating close to the maximum frequency of the device, and if frequency stability at start-up is not important for the application. 8.6 calibrated internal rc oscillator by default, the internal rc oscillator provides an approximate 8 mhz clock. though voltage and temperature dependent, this clock can be very accurately calibrated by the the user. see table 26-1 on page 266 for more details. the device is ship ped with the ckdiv8 fuse programmed. see ?system clock prescaler? on page 35 for more details. this clock may be selected as the system clock by programming the cksel fuses as shown in table 8-6 . if selected, it will operate with no external components. during reset, hardware loads the pre-programmed calibration value into the osccal register and thereby automatically cal- ibrates the rc oscillator. the accuracy of this calibration is shown as factory calibration in table 26-1 on page 266 . by changing the osccal register from sw, see ?osccal ? oscillator calibration register? on page 38 , it is possible to get a higher calibration accuracy than by using the factory calibration. the accuracy of this calibration is shown as user calibration in table 26-1 on page 266 . when this oscillator is used as the chip clock, the watchdog oscillator will still be used for the watchdog timer and for the reset time-out. for more information on the pre-programmed cali- bration value, see the section ?calibration byte? on page 249 . table 1. start-up times for the full swing crystal oscillator clock selection oscillator source / power conditions start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) cksel0 sut1..0 ceramic resonator, fast rising power 258 ck 14ck + 4.1 ms (1) 000 ceramic resonator, slowly rising power 258 ck 14ck + 65 ms (1) 001 ceramic resonator, bod enabled 1k ck 14ck (2) 010 ceramic resonator, fast rising power 1k ck 14ck + 4.1 ms (2) 011 ceramic resonator, slowly rising power 1k ck 14ck + 65 ms (2) 100 crystal oscillator, bod enabled 16k ck 14ck 1 01 crystal oscillator, fast rising power 16k ck 14ck + 4.1 ms 1 10 crystal oscillator, slowly rising power 16k ck 14ck + 65 ms 1 11 table 8-6. internal calibrated rc oscillator operating modes (3) frequency range (2) (mhz) cksel3..0 7.3 - 8.1 0010 (1)
34 7799d?avr?11/10 atmega8u2/16u2/32u2 notes: 1. the device is shipped with this option selected. 2. the frequency ranges are preliminary values. actual values are tbd. 3. if 8 mhz frequency exceeds the specification of the device (depends on v cc ), the ckdiv8 fuse can be programmed in order to divide the internal frequency by 8. when this oscillator is selected, start-up times are determined by the sut fuses as shown in table 8-5 on page 31 . note: 1. the device is shipped with this option selected. table 8-7. start-up times for the internal calibrated rc oscillator clock selection power conditions start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) sut1..0 bod enabled 6 ck 14 ck 00 fast rising power 6 ck 14 ck + 4.1 ms 01 slowly rising power 6 ck 14 ck + 65 ms (1) 10 reserved 11
35 7799d?avr?11/10 atmega8u2/16u2/32u2 8.7 external clock the device can utilize a external clock source as shown in figure 8-5 . to run the device on an external clock, the cksel fuses must be programmed as shown in table 8-1 . figure 8-5. external clock drive configuration when this clock source is selected, start-up times are determined by the sut fuses as shown in table 8-8 . when applying an external clock, it is required to avoid sudden changes in the applied clock fre- quency to ensure stable operation of the mcu. a variation in frequency of more than 2% from one clock cycle to the next can lead to unpredictable behavior. if changes of more than 2% is required, ensure that the mcu is kept in reset during the changes. note that the system clock prescaler can be used to implement run-time changes of the internal clock frequency while still ensuring stable operation. refer to ?system clock prescaler? on page 35 for details. 8.8 clock output buffer the device can output the system clock on the clko pin. to enable the output, the ckout fuse has to be programmed. this mode is suitable when the chip clock is used to drive other cir- cuits on the system. the clock also will be output during reset, and the normal operation of i/o pin will be overridden when the fuse is programmed. any clock source, including the internal rc oscillator, can be selected when the clock is output on clko. if the system clock prescaler is used, it is the divided system clock that is output. 8.9 system clock prescaler the atmega8u2/16u2/32u2 has a system clock prescaler, and the system clock can be divided by setting the ?clkpr ? clock prescale register? on page 39 . this feature can be used to table 8-8. start-up times for the external clock selection power conditions start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) sut1..0 bod enabled 6 ck 14ck 00 fast rising power 6 ck 14ck + 4.1 ms 01 slowly rising power 6 ck 14ck + 65 ms 10 reserved 11 nc external clock signal xtal2 xtal1 gnd
36 7799d?avr?11/10 atmega8u2/16u2/32u2 decrease the system clock frequency and the power consumption when the requirement for pro- cessing power is low. this can be used with all cl ock source options, and it will affect the clock frequency of the cpu and all synchronous peripherals. clk i/o , clk cpu , and clk flash are divided by a factor as shown in table 8-9 on page 40 . when switching between prescaler settings, the system clock prescaler ensures that no glitches occurs in the clock system. it also ensures that no intermediate frequency is higher than neither the clock frequency corresponding to the previous setting, nor the clock frequency corre- sponding to the new setting. the ripple counter that implements the prescaler runs at the frequency of the undivided clock, which may be faster than the cpu's clock frequency. hence, it is not possible to determine the state of the prescaler - even if it were readable, and the exact time it takes to switch from one clock division to the other cannot be exactly predicted. from the time the clkps values are writ- ten, it takes between t1 + t2 and t1 + 2 * t2 before the new clock frequency is active. in this interval, 2 active clock edges are produced. here, t1 is the previous clock period, and t2 is the period corresponding to the new prescaler setting. to avoid unintentional changes of clock frequenc y, a special write procedure must be followed to change the clkps bits: 1. write the clock prescaler change enable (clkpce) bit to one and all other bits in clkpr to zero. 2. within four cycles, write the desired value to clkps while writing a zero to clkpce. interrupts must be disabled when changing prescaler setting to make sure the write procedure is not interrupted. 8.10 pll the pll is used to generate internal high frequency (48 mhz) clock for usb interface, the pll input is generated from an external low-frequency (the crystal oscillator or external clock input pin from xtal1). 8.10.1 internal pll for usb interface the internal pll in atmega8u2/16u2/32u2 generates a clock frequency that is 6x multiplied from nominally 8 mhz input. the source of the 8 mhz pll input clock is the output of the internal pll clock prescaler that generates the 8 mhz.
37 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 8-6. pll clocking system 8.11 register description 8.11.1 clksel0 ? clock selection register 0 ? bit 7:6 ? rcsut[1:0]: sut for rc oscillator these 2 bits are the sut value for the rc oscillator. if the rc oscillator is selected by fuse bits, the sut fuse are copied into these bits. a firmware change will not have any effect because this additionnal start-up time is only used after a reset and not after a clock switch. ? bit 5:4 ? exsut[1:0]: sut for external oscillator / low power oscillator these 2 bits are the sut value for the external oscillator / low power oscillator. if the external oscillator / low power oscillator is selected by fuse bits, the sut fuse are copyed into these bits. the firmware can modify these bits by writing a new value. this value will be used at the next start of the external oscillator / low power oscillator. ? bit 3 ? rce: enable rc oscillator the rce bit must be written to logic one to enable the rc oscillator. the rce bit must be writ- ten to logic zero to disable the rc oscillator. ? bit 2 ? exte: enable external oscillator / low power oscillator the osce bit must be written to logic one to enable external oscillator / low power oscillator. the osce bit must be written to logic zero to disable the external oscillator / low power oscillator. ? bit 0 ? clks: clock selector the clks bit must be written to logic one to select the external oscillator / low power oscillator as cpu clock. the clks bit must be written to logic zero to select the rc oscillator as cpu clock. after a reset, the clks bit is set by hardware if the external oscillator / low power oscil- 8 mhz rc oscillator xtal1 xtal2 xtal oscillator pll plle lock detector tclk timer1 to system clock prescaler clk 8mhz pll clock prescaler pindiv pdiv3..0 clk usb /2 /48 pllitm pllusb 0 1 0 1 cksel3:0 plock t1 bit 7 6 5 4 3 2 1 0 (0xd0) rcsut1 rcsut0 exsut1 exsut0 rce exte - clks clksel0 read/write r/w r/w r/w r/w r/w r/w r r/w initial value 0 0 0 0 see bit description
38 7799d?avr?11/10 atmega8u2/16u2/32u2 lator is selected by the fuse bits configuration. the firmware has to check if the clock is correctly started before selected it. 8.11.2 clksel1 ? clock selection register 1 ? bit 7:4 ? rccksel[3:0]: cksel for rc oscillator clock configuration for the rc oscillator. after a reset, this part of the register is loaded with the 0010b value that corresponds to the rc oscillator. modifying this value by firmware before switching to rc oscillator is prohibited because the rc clock will not start. ? bit 3:0 ? excksel[3:0]: cksel for external oscillator / low power oscillator clock configuration for the external oscillator / low power oscillator. after a reset, if the exter- nal oscillator / low power oscillator is selected by fuse bits, this part of the register is loaded with the fuse configuration. firmware can modify it to change the start-up time after the clock switch. 8.11.3 clksta ? clock status register ? bit 7:2 - res: reserved bits these bits are reserved and will always read as zero. ? bit 1 ? rcon: rc oscillator on this bit is set by hardware to one if the rc oscillator is running. this bit is set by hardware to zero if the rc oscillator is stoped. ? bit 0 ? exton: external oscillator / low power oscillator on this bit is set by hardware to one if the external oscillator / low power oscillator is running. this bit is set by hardware to zero if the external oscillator / low power oscillator is stoped. 8.11.4 osccal ? oscillator calibration register ? bits 7:0 ? cal[7:0]: oscillator calibration value the oscillator calibration register is used to trim the calibrated internal rc oscillator to remove process variations from the oscillator frequency. a pre-programmed calibration value is automatically written to this register during chip reset, giving the factory calibrated frequency as specified in table 26-1 on page 266 . the application software can write this register to change bit 76543210 (0xd1) rcckse l3 rcckse l2 rcckse l1 rcckse l0 exckse l3 exckse l2 exckse l1 exckse l0 clksel1 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 1 0 0000 bit 76543210 (0xd2) - - - - - - rcon exton clksta read/write r r r r r r r r initial value 0 0 0 0 see bit description bit 76543210 (0x66) cal7 cal6 cal5 cal4 cal3 cal2 cal1 cal0 osccal read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value device specific calibration value
39 7799d?avr?11/10 atmega8u2/16u2/32u2 the oscillator frequency. the oscillator can be calibrated to frequencies as specified in table 26- 1 on page 266 . calibration outside that range is not guaranteed. note that this oscillator is used to time eeprom and flash write accesses, and these write times will be affected accordingly. if the eeprom or flash are written, do not calibrate to more than 8.8 mhz. otherwise, the eeprom or flash write may fail. the cal7 bit determines the range of operation for the oscillator. setting this bit to 0 gives the lowest frequency range, setting this bit to 1 gives the highest frequency range. the two fre- quency ranges are overlapping, in other words a setting of osccal = 0x7f gives a higher frequency than osccal = 0x80. the cal[6:0] bits are used to tune the frequency within the selected range. a setting of 0x00 gives the lowest frequency in that range, and a setting of 0x7f gives the highest frequency in the range. 8.11.5 clkpr ? clock prescale register ? bit 7 ? clkpce: clock prescaler change enable the clkpce bit must be written to logic one to enable change of the clkps bits. the clkpce bit is only updated when the other bits in clkpr are simultaneously written to zero. clkpce is cleared by hardware four cycles after it is written or when clkps bits are written. rewriting the clkpce bit within this time-out period does neither extend the time-out period, nor clear the clkpce bit. ? bit 6:4 - reserved bits these bits are reserved and will always read as zero. ? bits 3:0 ? clkps[3:0]: clock prescaler select bits 3 - 0 these bits define the division factor between the selected clock source and the internal system clock. these bits can be written run-time to vary the clock frequency to suit the application requirements. as the divider divides the master clock input to the mcu, the speed of all synchro- nous peripherals is reduced when a division factor is used. the division factors are given in table 8-9 . the ckdiv8 fuse determines the initial value of the clkps bits. if ckdiv8 is unprogrammed, the clkps bits will be reset to ?0000?. if ckdiv8 is programmed, clkps bits are reset to ?0011?, giving a division factor of 8 at start up. this feature should be used if the selected clock source has a higher frequency than the maximum frequency of the device at the present operat- ing conditions. note that any value can be writte n to the clkps bits regardless of the ckdiv8 fuse setting. the application software must ensure that a sufficient division factor is chosen if the selected clock source has a higher frequency than the maximum frequency of the device at the present operating conditions. the device is shipped with the ckdiv8 fuse programmed. bit 76543210 (0x61) clkpce ? ? ? clkps3 clkps2 clkps1 clkps0 clkpr read/write r/w r r r r/w r/w r/w r/w initial value 0 0 0 0 see bit description
40 7799d?avr?11/10 atmega8u2/16u2/32u2 8.11.6 pllcsr ? pll control and status register ? bit 7:5 ? res: reserved bits these bits are reserved bits in the atmega8u2/16u2/32u2 and always read as zero. ? bit 4 ? div5 pll input prescaler (1:5) ? bit 3 ? div3 pll input prescaler (1:3) ? bit 2 ? pindiv pll input prescaler (1:1, 1:2) these bits allow to configure the pll input prescaler to generate the 8mhz input clock for the pll from either a 8 or 16 mhz input. when using a 8 mhz clock source, this bit must be set to 0 before enabling pll (1:1). when using a 16 mhz clock source, this bit must be set to 1 before enabling pll (1:2). ? bit 3:2 ? res: reserved bits these bits are reserved and always read as zero. table 8-9. clock prescaler select clkps3 clkps2 clkps1 clkps0 clock division factor 0000 1 0001 2 0010 4 0011 8 0100 16 0101 32 0110 64 0111 128 1000 256 1 0 0 1 reserved 1 0 1 0 reserved 1 0 1 1 reserved 1 1 0 0 reserved 1 1 0 1 reserved 1 1 1 0 reserved 1 1 1 1 reserved bit 76543210 0x29 (0x49) ? ? ? div5 div3 pindiv plle plock pllcsr read/write r r r r/w r r r/w r initial value 0 0 000000
41 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 1 ? plle: pll enable when the plle is set, the pll is started. note that the calibrated 8 mhz internal rc oscillator is automatically enabled when the plle bit is set and with pinmux (see pllfrq register) is set. the pll must be disabled before entering power down mode in order to stop internal rc oscil- lator and avoid extra-consumption. ? bit 0 ? plock: pll lock detector when the plock bit is set, the pll is locked to the reference clock. after the pll is enabled, it takes about several ms for the pll to lock. to clear plock, clear plle.
42 7799d?avr?11/10 atmega8u2/16u2/32u2 9. power management and sleep modes 9.1 overview sleep modes enable the application to shut down unused modules in the mcu, thereby saving power. the avr provides various sleep modes al lowing the user to tailor the power consump- tion to the application?s requirements. 9.2 sleep modes figure 8-1 on page 26 presents the different clock systems in the atmega8u2/16u2/32u2, and their distribution. the figure is helpful in sele cting an appropriate sleep mode. shows the differ- ent sleep modes and their wake up sources. notes: 1. only recommended with external crystal or resonator selected as clock source. 2. for int[7:4], only level interrupt. 3. asynchronous usb interrupt is wakeupi only. to enter any of the five sleep modes, the se bit in smcr must be written to logic one and a sleep instruction must be executed. the sm2, sm1, and sm0 bits in the smcr register select which sleep mode (idle, power-down, power-save, standby or extended standby) will be acti- vated by the sleep instruction. see table 9-2 for a summary. if an enabled interrupt occurs while the mcu is in a sleep mode, the mcu wakes up. the mcu is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction following sleep. the contents of the register file and sram are unaltered when the device wakes up from sleep. if a reset occurs during sleep mode, the mcu wakes up and executes from the reset vector. 9.3 idle mode when the sm2:0 bits are written to 000, the sleep instruction makes the mcu enter idle mode, stopping the cpu but allowing the usb, spi, usart, analog comparator, timer/counters, table 9-1. active clock domains and wake-up sources in the different sleep modes. active clock domains oscillators wake-up sources sleep mode clk cpu clk flash clk io main clock source enabled int[7:0] and pcint12-0 spm/ eeprom ready wdt interrupt other i/o usb synchronous interrupts usb asynchonous interrupts (3) idle x x x x x x x x power-down x (2) xx power-save x (2) xx standby (1) xx (2) xx extended standby xx (2) xx
43 7799d?avr?11/10 atmega8u2/16u2/32u2 watchdog, and the interrupt system to continue operating. this sleep mode basically halts clk- cpu and clk flash , while allowing the other clocks to run. idle mode enables the mcu to wake up from external triggered interrupts as well as internal ones like the timer overflow, usart transmit complete or some usb interrupts (like sofi, wakeupi...). if wake-up from the analog comparator interrupt is not required, the analog com- parator can be powered down by setting the acd bit in the analog comparator control and status register ? acsr. this will reduce power consumption in idle mode. 9.4 power-down mode when the sm2:0 bits are written to 010, the sleep instruction makes the mcu enter power- down mode. in this mode, the external oscillator is stopped, while the external interrupts, the 2- wire serial interface, and the watchdog continue operating (if enabled). only an external reset, a watchdog reset, a brown-out reset, 2-wire serial interface address match, an external level interrupt on int7:4, an external interrupt on int3:0, a pin change interrupt or an asynchronous usb interrupt source (wakeupi only), can wake up the mcu. this sleep mode basically halts all generated clocks, allowing operation of asynchronous modules only. note that if a level triggered interrupt is used for wake-up from power-down mode, the changed level must be held for some time to wake up the mcu. refer to ?external interrupts? on page 84 for details. when waking up from power-down mode, there is a delay from the wake-up condition occurs until the wake-up becomes effective. this allows the clock to restart and become stable after having been stopped. the wake-up period is defined by the same cksel fuses that define the reset time-out period, as described in ?clock sources? on page 29 . 9.5 power-save mode when the sm2:0 bits are written to 011, the sleep instruction makes the mcu enter power- save mode. this mode is identical to power-down. this mode has been conserved for compati- bility purpose with higher-end products. 9.6 standby mode when the sm2:0 bits are 110 and an external crystal/resonator clock option is selected, the sleep instruction makes the mcu enter standby mode. this mode is identical to power-down with the exception that the oscillator is kept running. from standby mode, the device wakes up in six clock cycles. 9.7 extended standby mode when the sm2:0 bits are 111 and an external crystal/resonator clock option is selected, the sleep instruction makes the mcu enter extended standby mode. this mode is identical to power-save mode with the exception that the oscillator is kept running. so extended standby mode is equivalent to standy mode, but is also conserved for compatibility purpose. from extended standby mode, the device wakes up in six clock cycle. 9.8 power reduction register the power reduction registers (prr0 and prr1), provides a method to stop the clock to indi- vidual peripherals to reduce power consumption. see ?prr0 ? power reduction register 0? and ?prr1 ? power reduction register 1? on page 46 for details. the current state of the peripheral is frozen and the i/o registers can not be read or written. resources used by the peripheral
44 7799d?avr?11/10 atmega8u2/16u2/32u2 when stopping the clock will remain occupied, hence the peripheral should in most cases be dis- abled before stopping the clock. waking up a module, which is done by clearing the bit in prr, puts the module in the same state as before shutdown. module shutdown can be used in idle mode and active mode to significantly reduce the overall power consumption. 9.9 minimizing power consumption there are several issues to consider when trying to minimize the power consumption in an avr controlled system. in general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as few as possib le of the device?s functions are operating. all functions not needed should be disabled. in particular, the following modules may need special consideration when trying to achieve the lowest possible power consumption. 9.9.1 analog comparator when entering idle mode, the analog comparator should be disabled if not used. in other sleep modes, the analog comparator is automatically disabled. however, if the analog comparator is set up to use the internal voltage reference as input, the analog comparator should be dis- abled in all sleep modes. otherwise, the internal voltage reference will be enabled, independent of sleep mode. refer to ?analog comparator? on page 223 for details on how to configure the analog comparator. 9.9.2 brown-out detector if the brown-out detector is not needed by the application, this mod ule should be tu rned off. if the brown-out detector is enabled by the bodlevel fuses, it will be enabled in all sleep modes, and hence, always consume power. in the deeper sleep modes, this will contribute sig- nificantly to the total current consumption. refer to ?brown-out detection? on page 50 for details on how to configure the brown-out detector. 9.9.3 internal voltage reference the internal voltage reference will be enabled when needed by the brown-out detection, or the analog comparator. if these modules are disabled as described in the sections above, the inter- nal voltage reference will be disabled and it will not be consuming power. when turned on again, the user must allow the reference to start up before the output is used. if the reference is kept on in sleep mode, the output can be used immediately. refer to ?internal voltage reference? on page 51 for details on the start-up time. 9.9.4 watchdog timer if the watchdog timer is not needed in the application, the module should be turned off. if the watchdog timer is enabled, it will be enable d in all sleep modes, and hence, always consume power. in the deeper sleep modes, this will contribute significantly to the total current consump- tion. refer to ?interrupts? on page 64 for details on how to configure the watchdog timer. 9.9.5 port pins when entering a sleep mode, all port pins should be configured to use minimum power. the most important is then to ensure that no pins drive resistive loads. in sleep modes where the i/o clock (clk i/o ) is stopped, the input buffers of the device will be disabled. this ensures that no power is consumed by the input logic when not needed. in some cases, the input logic is needed for detecting wake-up conditions, and it will then be enabled. refer to the section ?digital input enable and sleep modes? on page 71 for details on which pins are enabled. if the input buffer is
45 7799d?avr?11/10 atmega8u2/16u2/32u2 enabled and the input signal is left floating or have an analog signal level close to v cc /2, the input buffer will use excessive power. for analog input pins, the digital input buffer should be disabled at all times. an analog signal level close to v cc /2 on an input pin can cause significant current even in active mode. digital input buffers can be disabled by writing to the digital input disable registers (didr1). refer to ?didr1 ? digital input disable register 1? on page 225 for details. 9.9.6 on-chip debug system if the on-chip debug system is enabled by the ocden fuse and the chip enters sleep mode, the main clock source is enabled, and hence, always consumes power. in the deeper sleep modes, this will contribute significantly to the total current consumption. 9.10 register description 9.10.1 smcr ? sleep mode control register the sleep mode control register contains control bits for power management. ? bit 7:4 - reserved bits these bits are reserved and will always read as zero. ? bits 3:1 ? sm[2:0]: sleep mode select bits 2, 1, and 0 these bits select between the five available sleep modes as shown in table 9-2 . note: 1. standby modes are only recommended for use with external crystals or resonators. ? bit 0? se: sleep enable the se bit must be written to logic one to make the mcu enter the sleep mode when the sleep instruction is executed. to avoid the mcu entering the sleep mode unless it is the programmer?s purpose, it is recommended to write the sleep enable (se) bit to one just before the execution of the sleep instruction and to clear it immediately after waking up. bit 76543210 0x33 (0x53) ? ? ? ? sm2 sm1 sm0 se smcr read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 9-2. sleep mode select sm2 sm1 sm0 sleep mode 0 0 0 idle 0 0 1 reserved 0 1 0 power-down 0 1 1 power-save 1 0 0 reserved 1 0 1 reserved 1 1 0 standby (1) 1 1 1 extended standby (1)
46 7799d?avr?11/10 atmega8u2/16u2/32u2 9.10.2 prr0 ? power reduction register 0 ? bit 7:6 - res: reserved bits these bits are reserved and will always read as zero. ? bit 5 - prtim0: power reduction timer/counter0 writing a logic one to this bit shuts down the timer/counter0 module. when the timer/counter0 is enabled, operation will continue like before the shutdown. ? bit 4 - res: reserved bit this bit is reserved and will always read as zero. ? bit 3 - prtim1: power reduction timer/counter1 writing a logic one to this bit shuts down the timer/counter1 module. when the timer/counter1 is enabled, operation will continue like before the shutdown. ? bit 2 - prspi: power reduction serial peripheral interface writing a logic one to this bit shuts down the serial peripheral interface by stopping the clock to the module. when waking up the spi again, the spi should be re initialized to ensure proper operation. ? bit 1 - res: reserved bit these bits are reserved and will always read as zero. ? bit 0 - res: reserved bit these bits are reserved and will always read as zero. 9.10.3 prr1 ? power reduction register 1 ? bit 7 - prusb: power reduction usb writing a logic one to this bit shuts down the usb by stopping the clock to the module. when waking up the usb again, the usb should be re initialized to ensure proper operation. ? bit 6:1 - res: reserved bits these bits are reserved and will always read as zero. ? bit 0 - prusart1: power reduction usart1 writing a logic one to this bit shuts down the usart1 by stopping the clock to the module. when waking up the usart1 again, the usart1 should be re initialized to ensure proper operation. bit 7 6 5 4 3 2 1 0 (0x64) - - prtim0 ? prtim1 prspi - - prr0 read/write r/w r/w r/w r r/w r/w r r/w initial value 0 0 0 0 0 0 0 0 bit 7 6 5 4 3 2 1 0 (0x65) prusb ? ? ? - ? ? prusart1 prr1 read/write r/w r r r r/w r r r/w initial value 0 0 0 0 0 0 0 0
47 7799d?avr?11/10 atmega8u2/16u2/32u2 10. system control and reset 10.1 resetting the avr during reset, all i/o registers are set to their initial values, and the program starts execution from the reset vector. the instruction placed at the reset vector must be a jmp ? absolute jump ? instruction to the reset handling routine. if the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the reset vector is in the application section while the interrupt vectors are in the boot section or vice versa. the circuit diagram in figure 10-1 shows the reset logic. ?system and reset characteristics? on page 267 defines the electrical parameters of the reset circuitry. the i/o ports of the avr are immediately reset to their initial state when a reset source goes active. this does not require any clock source to be running. after all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. this allows the power to reach a stable level before normal operation starts. the time-out period of the delay counter is defined by the user through the sut and cksel fuses. the dif- ferent selections for the delay period are presented in ?clock sources? on page 29 . 10.2 reset sources the atmega8u2/16u2/32u2 has five sources of reset: ? power-on reset. the mcu is reset when the supply voltage is below the power-on reset threshold (v pot ). ? external reset. the mcu is reset when a low level is present on the reset pin for longer than the minimum pulse length. ? watchdog reset. the mcu is reset when the watchdog timer period expires and the watchdog is enabled. ? brown-out reset. the mcu is reset when the supply voltage v cc is below the brown-out reset threshold (v bot ) and the brown-out detector is enabled. ? usb reset. the mcu is reset when the usb macro is enabled and detects a usb reset. note that with this reset the usb macro remains enabled so that the device stays attached to the bus.
48 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 10-1. reset logic 10.2.1 power-on reset a power-on reset (por) pulse is generated by an on-chip detection circuit. the detection level is defined in ?system and reset characteristics? on page 267 . the por is activated whenever v cc is below the detection level. the por circuit can be used to trigger the start-up reset, as well as to detect a failure in supply voltage. a power-on reset (por) circuit ensures that th e device is reset from power-on. reaching the power-on reset threshold voltage invokes the delay counter, which determines how long the device is kept in reset after v cc rise. the reset signal is activated again, without any delay, when v cc decreases below the detection level. figure 10-2. mcu start-up, reset tied to v cc mcu status register (mcusr) brown-out reset circuit bodlevel [2..0] delay counters cksel[3:0] ck timeout wdrf borf extrf porf data bus clock generator spike filter pull-up resistor usbrf usb device reset detection watchdog oscillator sut[1:0] power-on reset circuit v reset time-out internal reset t tout v pot v rst cc
49 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 10-3. mcu start-up, reset extended externally 10.2.2 external reset an external reset is generated by a low level on the r e s e t pin. reset pulses longer than the minimum pulse width (see ?system and reset characteristics? on page 267 ) will generate a reset, even if the clock is not running. shorter pulses are not guaranteed to generate a reset. when the applied signal reaches the reset threshold voltage ? v rst ? on its positive edge, the delay counter starts the mcu after the time-out period ? t tout ? has expired. figure 10-4. external reset during operation reset time-out internal reset t tout v pot v rst v cc cc
50 7799d?avr?11/10 atmega8u2/16u2/32u2 10.2.3 brown-out detection atmega8u2/16u2/32u2 has an on-chip brown-out detection (bod) circuit for monitoring the v cc level during operation by comparing it to a fixed trigger level. the trigger level for the bod can be selected by the bodlevel fuses. the trigger level has a hysteresis to ensure spike free brown-out detection. the hysteresis on the detection level should be interpreted as v bot+ = v bot + v hyst /2 and v bot- = v bot - v hyst /2. when the bod is enabled, and v cc decreases to a value below the trigger level (v bot- in figure 10-5 ), the brown-out reset is immediately acti- vated. when v cc increases above the trigger level (v bot+ in figure 10-5 ), the delay counter starts the mcu after the time-out period t tout has expired. the bod circuit will only detect a drop in v cc if the voltage stays below the trigger level for lon- ger than t bod given in ?system and reset characteristics? on page 267 . figure 10-5. brown-out reset during operation 10.2.4 watchdog reset when the watchdog times out, it will generate a short reset pulse of one ck cycle duration. on the falling edge of this pulse, the delay timer starts counting the time-out period t tout . refer to ?watchdog timer? on page 51 for details on operation of the watchdog timer. figure 10-6. watchdog reset during operation 10.2.5 usb reset when the usb macro is enabled and configured with the usb reset mcu feature enabled, and if a valid usb reset signalling is detected, the microcontroller is reset unless the usb macro v cc reset time-out internal reset v bot- v bot+ t tout ck cc
51 7799d?avr?11/10 atmega8u2/16u2/32u2 that remains enabled. this allows the device to stay attached to the bus during and after the reset, while enhancing firmware reliability. figure 10-7. usb reset during operation 10.3 internal voltage reference atmega8u2/16u2/32u2 features an internal bandgap reference. this reference is used for brown-out detection, and it can be used as an input to the analog comparator. 10.3.1 voltage reference enable signals and start-up time the voltage reference has a start-up time that may influence the way it should be used. the start-up time is given in ?system and reset characteristics? on page 267 . to save power, the reference is not always turned on. the reference is on during the following situations: 1. when the bod is enabled (by programming the bodlevel [2..0] fuse). 2. when the bandgap reference is connected to the analog comparator (by setting the acbg bit in acsr). thus, when the bod is not enabled, after setting the acbg bit, the user must always allow the reference to start up before the output from the analog comparator is used. to reduce power consumption in power-down mode, the user can avoid the three conditions above to ensure that the reference is turned off before entering power-down mode. 10.4 watchdog timer 10.4.1 features ? clocked from separate on-chip oscillator ? 3 operating modes ? interrupt ? system reset ? interrupt and system resetselectable time-out period from 16ms to 8s ? possible hardware fuse watchdog always on (wdton) for fail-safe mode ? early warning after one time-out period reached, programmable reset (see operating modes) after 2 time-out periods reached. 10.4.2 overview atmega8u2/16u2/32u2 has an enhanced watchdog timer (wdt). the wdt is a timer count- ing cycles of a separate on-chip 128 khz oscillator. the wdt gives a early warning interrupt cc usb traffic usb traffic dp dm (usb lines) t usbrstmin end of reset
52 7799d?avr?11/10 atmega8u2/16u2/32u2 when the counter reaches a given time-out value. the wdt gives an interrupt or a system reset when the counter reaches two times the given time-out value. in normal operation mode, it is required that the system uses the wdr - watchdog timer reset - instruction to restart the coun- ter before the time-out value is reached. if the system doesn't restart the counter, an interrupt or system reset will be issued. figure 10-8. watchdog timer in interrupt mode, the wdt gives an interrupt when the timer expires two times. this interrupt can be used to wake the device from sleep-modes, and also as a general system timer. one example is to limit the maximum time allowed for certain operations, giving an interrupt when the operation has run longer than expected. in system reset mode, the wdt gives a reset when the timer expires two times. this is typically used to prevent system hang-up in case of runaway code. the third mode, interrupt and system reset mode, combines the other two modes by first giving an interrupt and then switch to system reset mode. this mode will for instance allow a safe shutdown by saving critical parameters before a system reset. in addition to these modes, the early warning inte rrupt can be enabled in order to generate an interrupt when the wdt counter expires the first time. the watchdog always on (wdton) fuse, if programmed, will force the watchdog timer to sys- tem reset mode. with the fuse programmed the system reset mode bit (wde) and interrupt mode bit (wdie) are locked to 1 and 0 respectively. to further ensure program security, altera- tions to the watchdog set-up must follow timed sequences. the sequence for clearing wde or changing time-out configuration is as follows: 1. in the same operation, write a logic one to the watchdog change enable bits wdce and wde. a logic one must be written to wde regardless of the previous value of the wde bit and even if it will be cleared after the operation. 2. within the next four clock cycles, write the wde and watchdog prescaler bits (wdp) as desired, but with the wdce bit cleared. this must be done in one operation. 128khz oscillator osc/2k osc/4k osc/8k osc/16k osc/32k osc/64k osc/128k osc/256k osc/512k osc/1024k wdp0 wdp1 wdp2 wdp3 watchdog reset wde wdif wdie wdewie mcu reset interrupt early warning interrupt clock divider wclkd0 wclkd1 osc/1 osc/3 osc/5 osc/7
53 7799d?avr?11/10 atmega8u2/16u2/32u2 while the wdt prescaler allows only even division factors (2, 4, 8...), the wdt peripheral also includes a clock divider that directly acts on th e clock source. this divider handles odd division factors (3, 5, 7). in combination with the prescaler, a large number of time-out values can be obtained. the divider factor change is also ruled by the secure timed sequence : first the wde and wdce bits must be set, and then four cycles are available to load the new divider value into the wdtckd register. be aware that after this operation wde will still be set. so keep in mind the importance of order of operations. when setting up the wdt in interrupt mode with specific val- ues of prescaler and divider, the divider register must be loaded before the prescaler register : 1. set wdce and wde 2. load the divider factor into wdtckd 3. wait wdce being automatically cleared (just wait 2 more cycles) 4. set again wdce and wde 5. clear wde, set wdie and load the prescaler factor into wdtcsr in a same operation 6. now the system is properly configured for interrupt only mode. inverting the two opera- tions would have been resulted into ?reset and interrupt mode? and needed a third operation to clear wde. the following code example shows one assembly and one c function for turning off the watch- dog timer. the example assumes that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during the execution of these functions.
54 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. the example code assumes that the part specific header file is included. note: if the watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be rese t and the watchdog timer will st ay enabled. if the code is not set up to handle the watchdog, this might lead to an eternal loop of time-out resets. to avoid this situation, the application software should always clear the watchdog system reset flag (wdrf) and the wde control bit in the initialisation routine, even if the watchdog is not in use. the following code example shows one assembly and one c function for changing the time-out value of the watchdog timer. assembly code example (1) wdt_off: ; turn off global interrupt cli ; reset watchdog timer wdr ; clear wdrf in mcusr in r16, mcusr andi r16, (0xff & (0< 55 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. the example code assumes that the part specific header file is included. note: the watchdog timer should be reset before any change of the wdp bits, since a change in the wdp bits can result in a time-out when switching to a shorter time-out period. 10.5 register description 10.5.1 mcusr ? mcu status register the mcu status register provides information on which reset source caused an mcu reset. ? bit 7:6 ? res: reserved bit these bits are reserved and will always read as zero. assembly code example (1) wdt_prescaler_change: ; turn off global interrupt cli ; reset watchdog timer wdr ; start timed sequence in r16, wdtcsr ori r16, (1< 56 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 5 ? usbrf: usb reset flag this bit is set if a usb reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 4 ? res: reserved bit this bit is reserved and will always read as zero. ? bit 3 ? wdrf: watchdog reset flag this bit is set if a watchdog reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 2 ? borf: brown-out reset flag this bit is set if a brown-out reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 1 ? extrf: external reset flag this bit is set if an external reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 0 ? porf: power-on reset flag this bit is set if a power-on reset occurs. the bit is reset only by writing a logic zero to the flag. to make use of the reset flags to identify a reset condition, the user should read and then reset the mcusr as early as possible in the program. if the register is cleared before another reset occurs, the source of the reset can be found by examining the reset flags. 10.5.2 wdtcsr ? watchdog timer control register ? bit 7 - wdif: watchdog interrupt flag this bit is set when a time-out occurs twice in the watchdog timer and if the watchdog timer is configured for interrupt. wdif is automatically cleared by hardware when executing the corre- sponding interrupt handling vector. alternatively, wdif is cleared by writing a logic one to the flag. when the i-bit in sreg and wdie are set, the watchdog time-out interrupt is executed. ? bit 6 - wdie: watchdog interrupt enable when this bit is written to one and the i-bit in the status register is set, the watchdog interrupt is enabled. if wde is cleared in combination with this setting, the watchdog timer is in interrupt mode, and the corresponding interrupt is executed if time-out in the watchdog timer occurs. if wde is set, the watchdog timer is in interrupt and system reset mode. two consecutives times-out in the watchdog timer will set wdif. executing the corresponding interrupt vector will clear wdie and wdif automatically by hardware : the watchdog goes to system reset mode. this is useful for keeping the watchdog timer security while using the interrupt. to reinitialize the interrupt and system reset mode, wdie must be set after each interrupt. this should how- ever not be done within the interrupt service routine itself, as this might compromise the safety- bit 76543210 (0x60) wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 wdtcsr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 x 0 0 0
57 7799d?avr?11/10 atmega8u2/16u2/32u2 function of the watchdog system reset mode. if the interrupt is not executed before the next time-out, a system reset will be applied. ? bit 4 - wdce: watchdog change enable this bit is used in timed sequences for changing wde and prescaler bits. to clear the wde bit, and/or change the prescaler bits, wdce must be set. once written to one, hardware will clear wdce after four clock cycles. ? bit 3 - wde: watchdog system reset enable wde is overridden by wdrf in mcusr. this means that wde is always set when wdrf is set. to clear wde, wdrf must be cleared first. this feature ensures multiple resets during con- ditions causing failure, and a safe start-up after the failure. ? bit 5, 2:0 - wdp[3:0]: watchdog timer prescaler 3, 2, 1 and 0 the wdp3..0 bits determine the watchdog timer prescaling when the watchdog timer is run- ning. the different prescaling values and their corresponding time-out periods are shown in table on page 58 . 10.5.3 wdtckd ? watchdog timer clock divider register ? bit 7:6 - res: reserved bits these bits are reserved and will always read as zero. ? bit 5 - wdewifcl: watchdog early warning flag clear mode when this bit has been set by so ftware, the wdewif interrupt fl ag is not cleared by hardware when entering the watchdog interrupt subroutine (it has to be cleared by software by writing a logic one to the flag). when cleared, the wdewif is cleared by hardware when executing the corresponding interrupt handling vector. ? bit 4 - wclkd2 bit: watchdog timer clock divider see ?bit 1:0 - wclkd[1:0]: watchdog timer clock divider? on page 58 . table 10-1. watchdog timer configuration wdton (fuse) wde wdie mode action on 2x time-out 1 (unprogrammed) 0 0 stopped none 1 (unprogrammed) 0 1 interrupt mode interrupt 1 (unprogrammed) 1 0 system reset mode reset 1 (unprogrammed) 1 1 interrupt and system reset mode interrupt, then go to system reset mode 0 (programmed) x x system reset mode reset bit 7 6 5 4 3 2 1 0 (0x62) - - wdewif- cm wclkd2 wdewif wdewie wclkd1 wclkd0 wdtckd read/write r r r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
58 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 3 - wdewif: watchdog early warning interrupt flag this bit is set when a first time-out occurs in the watchdog timer and if the wdewie bit is enabled. wdewif is automatically cleared by hardware when executing the corresponding interrupt handling vector. alternatively, wdif can be cleared by writing a logic one to the flag. when the i-bit in sreg and wdewie are set, the watchdog time-out interrupt is executed. ? bit 2 - wdewie: watchdog early warning interrupt enable when this bit has been set by software, an interrupt will be generated on the watchdog interrupt vector when the early warning flag is set to one by hardware. ? bit 1:0 - wclkd[1:0]: watchdog timer clock divider table 10-2. watchdog timer clock divider configuration wclkd2 wclkd1 wclkd0 mode 000 clk wdt = clk 128k 001 clk wdt = clk 128k / 3 010 clk wdt = clk 128k / 5 011 clk wdt = clk 128k / 7 100 clk wdt = clk 128k / 9 101 clk wdt = clk 128k / 11 110 clk wdt = clk 128k / 13 111 clk wdt = clk 128k / 15 table 10-3. watchdog timer prescale select, div = 0 (clkwdt = clk128 / 1) wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles before 1st time-out (early warning) early warning typical time-out at v cc = 5.0v watchdog reset/interrupt typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 16 ms 32 ms 0 0 0 1 4k (4096) cycles 32 ms 64 ms 0 0 1 0 8k (8192) cycles 64 ms 128 ms 0 0 1 1 16k (16384) cycles 0.125 s 0.250 s 0 1 0 0 32k (32768) cycles 0.25 s 0.5 s 0 1 0 1 64k (65536) cycles 0.5 s 1.0 s 0 1 1 0 128k (131072) cycles 1.0 s 2.0 s 0 1 1 1 256k (262144) cycles 2.0 s 4.0 s 1 0 0 0 512k (524288) cycles 4.0 s 8.0 s 1 0 0 1 1024k (1048576) cycles 8.0 s 16.0 s
59 7799d?avr?11/10 atmega8u2/16u2/32u2 1010 reserved 1011 1100 1101 1110 1111 table 10-3. watchdog timer prescale select, div = 0 (clkwdt = clk128 / 1) (continued) wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles before 1st time-out (early warning) early warning typical time-out at v cc = 5.0v watchdog reset/interrupt typical time-out at v cc = 5.0v table 10-4. watchdog timer prescale select, div = 1 (clkwdt = clk128 / 3) wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles before 1st time-out (early warning) early warning typical time-out at v cc = 5.0v watchdog reset/interrupt typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 48 ms 96 ms 0 0 0 1 4k (4096) cycles 96 ms 192 ms 0 0 1 0 8k (8192) cycles 192 ms 384 ms 0 0 1 1 16k (16384) cycles 0.375 s 0.75 s 0 1 0 0 32k (32768) cycles 0.75 s 1.5 s 0 1 0 1 64k (65536) cycles 1.5 s 3 s 0 1 1 0 128k (131072) cycles 3 s 6 s 0 1 1 1 256k (262144) cycles 6 s 12 s 1 0 0 0 512k (524288) cycles 12 s 24 s 1 0 0 1 1024k (1048576) cycles 24 s 48 s 1010 reserved 1011 1100 1101 1110 1111
60 7799d?avr?11/10 atmega8u2/16u2/32u2 table 10-5. watchdog timer prescale select, div = 2 (clkwdt = clk128 / 5) wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles before 1st time-out (early warning) early warning typical time-out at v cc = 5.0v watchdog reset/interrupt typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 80 ms 160 ms 0 0 0 1 4k (4096) cycles 160 ms 320 ms 0 0 1 0 8k (8192) cycles 320 ms 640 ms 0 0 1 1 16k (16384) cycles 0.625 s 1.25 s 0 1 0 0 32k (32768) cycles 1.25 s 2.5 s 0 1 0 1 64k (65536) cycles 2.5 s 5 s 0 1 1 0 128k (131072) cycles 5 s 10 s 0 1 1 1 256k (262144) cycles 10 s 20 s 1 0 0 0 512k (524288) cycles 20 s 40 s 1 0 0 1 1024k (1048576) cycles 40 s 80 s 1010 reserved 1011 1100 1101 1110 1111 table 10-6. watchdog timer prescale select, div = 3 (clkwdt = clk128 / 7) wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles before 1st time-out (early warning) early warning typical time-out at v cc = 5.0v watchdog reset/interrupt typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 112 ms 224 ms 0 0 0 1 4k (4096) cycles 224 ms 448 ms 0 0 1 0 8k (8192) cycles 448 ms 896 ms 0 0 1 1 16k (16384) cycles 0.875 s 1.75 s 0 1 0 0 32k (32768) cycles 1.75 s 3.5 s 0 1 0 1 64k (65536) cycles 3.5 s 7 s 0 1 1 0 128k (131072) cycles 7 s 14 s 0 1 1 1 256k (262144) cycles 14 s 28 s 1 0 0 0 512k (524288) cycles 28 s 56 s 1 0 0 1 1024k (1048576) cycles 56 s 112 s
61 7799d?avr?11/10 atmega8u2/16u2/32u2 1010 reserved 1011 1100 1101 1110 1111 table 10-6. watchdog timer prescale select, div = 3 (clkwdt = clk128 / 7) (continued) wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles before 1st time-out (early warning) early warning typical time-out at v cc = 5.0v watchdog reset/interrupt typical time-out at v cc = 5.0v table 10-7. watchdog timer prescale select, div = 4 (clkwdt = clk128 / 9) wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles before 1st time-out (early warning) early warning typical time-out at v cc = 5.0v watchdog reset/interrupt typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 72ms 144 ms 0 0 0 1 4k (4096) cycles 144 ms 288 ms 0 0 1 0 8k (8192) cycles 288 ms 576 ms 0 0 1 1 16k (16384) cycles 576 s 1.15 s 0 1 0 0 32k (32768) cycles 1.1 s 2.3 s 0 1 0 1 64k (65536) cycles 2.3 s 4.6 s 0 1 1 0 128k (131072) cycles 4.6 s 9.2 s 0 1 1 1 256k (262144) cycles 9.2 s 18.4s 1 0 0 0 512k (524288) cycles 18.4 s 36.8 s 1 0 0 1 1024k (1048576) cycles 36.8 s 73 s 1010 reserved 1011 1100 1101 1110 1111
62 7799d?avr?11/10 atmega8u2/16u2/32u2 table 10-8. watchdog timer prescale select, div = 5 (clkwdt = clk128 / 11) wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles before 1st time-out (early warning) early warning typical time-out at v cc = 5.0v watchdog reset/interrupt typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 88 ms 176 ms 0 0 0 1 4k (4096) cycles 176 ms 352 ms 0 0 1 0 8k (8192) cycles 352 ms 704 ms 0 0 1 1 16k (16384) cycles 704 ms 1.4 s 0 1 0 0 32k (32768) cycles 1.4 s 2.8 s 0 1 0 1 64k (65536) cycles 2.8 s 5.6 s 0 1 1 0 128k (131072) cycles 5.6 s 11.2 s 0 1 1 1 256k (262144) cycles 11.2 s 22.5 s 1 0 0 0 512k (524288) cycles 22.5 s 45 s 1 0 0 1 1024k (1048576) cycles 45s 90 s 1010 reserved 1011 1100 1101 1110 1111 table 10-9. watchdog timer prescale select, div = 6(clkwdt = clk128 / 13) wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles before 1st time-out (early warning) early warning typical time-out at v cc = 5.0v watchdog reset/interrupt typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 104 ms 208 ms 0 0 0 1 4k (4096) cycles 208 ms 416 ms 0 0 1 0 8k (8192) cycles 416 ms 832 ms 0 0 1 1 16k (16384) cycles 832 ms 1.64 s 0 1 0 0 32k (32768) cycles 1.6 s 3.3 s 0 1 0 1 64k (65536) cycles 3.3 s 6.6 s 0 1 1 0 128k (131072) cycles 6.6 s 13.3 s 0 1 1 1 256k (262144) cycles 13.3 s 26.6 s 1 0 0 0 512k (524288) cycles 26.6 s 53.2 s 1 0 0 1 1024k (1048576) cycles 53.2 s 106.4 s
63 7799d?avr?11/10 atmega8u2/16u2/32u2 1010 reserved 1011 1100 1101 1110 1111 table 10-9. watchdog timer prescale select, div = 6(clkwdt = clk128 / 13) (continued) wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles before 1st time-out (early warning) early warning typical time-out at v cc = 5.0v watchdog reset/interrupt typical time-out at v cc = 5.0v table 10-10. watchdog timer prescale select, div = 7 (clkwdt = clk128 / 15) wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles before 1st time-out (early warning) early warning typical time-out at v cc = 5.0v watchdog reset/interrupt typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 120 ms 240 ms 0 0 0 1 4k (4096) cycles 240 ms 480 ms 0 0 1 0 8k (8192) cycles 480 ms 960 ms 0 0 1 1 16k (16384) cycles 0.960 s 1.9 s 0 1 0 0 32k (32768) cycles 1.92 s 3.8 s 0 1 0 1 64k (65536) cycles 3.8 s 7.6 s 0 1 1 0 128k (131072) cycles 7.6 s 15.3 s 0 1 1 1 256k (262144) cycles 15.3 s 30.7 s 1 0 0 0 512k (524288) cycles 30.7 s 61.4 s 1 0 0 1 1024k (1048576) cycles 61.4 s 122 s 1010 reserved 1011 1100 1101 1110 1111
64 7799d?avr?11/10 atmega8u2/16u2/32u2 11. interrupts 11.1 overview this section describes the specifics of the interrupt handling as performed in atmega8u2/16u2/32u2. for a general explanation of the avr interrupt handling, refer to ?reset and interrupt handling? on page 13 . 11.2 interrupt vectors in atmega8u2/16u2/32u2 table 11-1. reset and interrupt vectors vector no. program address (2) source interrupt definition 1 $0000 (1) reset external pin, power-on reset, brown-out reset, watchdog reset, usb reset and debugwire avr reset 2 $0002 int0 external interrupt request 0 3 $0004 int1 external interrupt request 1 4 $0006 int2 external interrupt request 2 5 $0008 int3 external interrupt request 3 6 $000a int4 external interrupt request 4 7 $000c int5 external interrupt request 5 8 $000e int6 external interrupt request 6 9 $0010 int7 external interrupt request 7 10 $0012 pcint0 pin change interrupt request 0 11 $0014 pcint1 pin change interrupt request 1 12 $0016 usb general usb general interrupt request 13 $0018 usb endpoint usb endpoint interrupt request 14 $001a wdt watchdog time-out interrupt 15 $001c timer1 capt timer/counter1 capture event 16 $001e timer1 compa timer/counter1 compare match a 17 $0020 timer1 compb timer/counter1 compare match b 18 $0022 timer1 compc timer/counter1 compare match c 19 $0024 timer1 ovf timer/counter1 overflow 20 $0026 timer0 compa timer/counter0 compare match a 21 $0028 timer0 compb timer/counter0 compare match b 22 $002a timer0 ovf timer/counter0 overflow 23 $002c spi, stc spi serial transfer complete 24 $002e usart1 rx usart1 rx complete 25 $0030 usart1 udre usart1 data register empty 26 $0032 usart1tx usart1 tx complete
65 7799d?avr?11/10 atmega8u2/16u2/32u2 notes: 1. when the bootrst fuse is programmed, the device will jump to the boot loader address at reset, see ?memory programming? on page 246 . 2. when the ivsel bit in mcucr is set, interrupt vectors will be moved to the start of the boot flash section. the address of each interrupt vector will then be the address in this table added to the start address of the boot flash section. moreover, contrary to other 8k/16k devices, the interrupt vectors spacing remains identical (2 words) for both 8kb and 16kb versions. table 11-2 shows reset and interrupt vectors placement for the various combinations of bootrst and ivsel settings. if the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the reset vector is in the application section while the interrupt vectors are in the boot section or vice versa. note: 1. the boot reset address is shown in table 23-8 on page 239 . for the bootrst fuse ?1? means unprogrammed while ?0? means programmed. 11.2.1 moving interrupts between application and boot space the general interrupt control register controls the placement of the interrupt vector table. 11.3 register description 11.3.1 mcucr ? mcu control register ? bit 1 ? ivsel: interrupt vector select when the ivsel bit is cleared (zero), the interrupt vectors are placed at the start of the flash memory. when this bit is set (one), the interrupt vectors are moved to the beginning of the boot loader section of the flash. the actual address of the start of the boot flash section is deter- mined by the bootsz fuses. refer to the section ?memory programming? on page 246 for details. to avoid unintentional changes of interrupt vector tables, a special write procedure must be followed to change the ivsel bit: 27 $0034 analog comp analog comparator 28 $0036 ee ready eeprom ready 29 $0038 spm ready store program memory ready table 11-2. reset and interrupt vectors placement (1) bootrst ivsel reset address interrupt vectors start address 1 0 0x0000 0x0002 1 1 0x0000 boot reset address + 0x0002 0 0 boot reset address 0x0002 0 1 boot reset address boot reset address + 0x0002 table 11-1. reset and interrupt vectors (continued) vector no. program address (2) source interrupt definition bit 76543210 0x35 (0x55) jtd ? ? pud ? ? ivsel ivce mcucr read/write r/w r r r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0
66 7799d?avr?11/10 atmega8u2/16u2/32u2 a. write the interrupt vector change enable (ivce) bit to one. b. within four cycles, write the desired value to ivsel while writing a zero to ivce. interrupts will automatically be disabled while this sequence is executed. interrupts are disabled in the cycle ivce is set, and they remain disabled until after the instruction following the write to ivsel. if ivsel is not written, interrupts remain disabled for four cycles. the i-bit in the status register is unaffected by the automatic disabling. note: if interrupt vectors are placed in the boot loader section and boot lock bit blb02 is pro- grammed, interrupts are disabled while executing from the application section. if interrupt vectors are placed in the application section and boot lock bit blb12 is programed, interrupts are dis- abled while executing from the boot loader section. refer to the section ?memory programming? on page 246 for details on boot lock bits. ? bit 0 ? ivce: interrupt vector change enable the ivce bit must be written to logic one to enable change of the ivsel bit. ivce is cleared by hardware four cycles after it is written or when ivsel is written. setting the ivce bit will disable interrupts, as explained in the ivsel description above. see code example below. assembly code example move_interrupts: ; enable change of interrupt vectors ldi r16, (1< 67 7799d?avr?11/10 atmega8u2/16u2/32u2 12. i/o-ports 12.1 overview all avr ports have true read-modify-write functionality when used as general digital i/o ports. this means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the sbi and cbi instructions. the same applies when chang- ing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input). each output buffer has symmetrical drive characteristics with both high sink and source capability. the pin driver is strong enough to drive led displays directly. all port pins have indi- vidually selectable pull-up resistors with a supply-voltage invariant resistance. all i/o pins have protection diodes to both v cc and ground as indicated in figure 12-1 . refer to ?electrical char- acteristics? on page 264 for a complete list of parameters. figure 12-1. i/o pin equivalent schematic all registers and bit references in this section are written in general form. a lower case ?x? repre- sents the numbering letter for the port, and a lower case ?n? represents the bit number. however, when using the register or bit defines in a program, the precise form must be used. for example, portb3 for bit no. 3 in port b, here documented generally as portxn. the physical i/o regis- ters and bit locations are listed in ?register description for i/o-ports? on page 82 . three i/o memory address locations are allocated for each port, one each for the data register ? portx, data direction register ? ddrx, and the port input pins ? pinx. the port input pins i/o location is read only, while the data register and the data direction register are read/write. however, writing a logic one to a bit in the pinx register, will result in a toggle in the correspond- ing bit in the data register. in addition, the pull-up disable ? pud bit in mcucr disables the pull-up function for all pins in all ports when set. using the i/o port as genera l digital i/o is described in ?ports as general digit al i/o? on page 68 . most port pins are multiplexed with alternate functions for the peripheral features on the device. how each alternate function interferes with the port pin is described in ?alternate port functions? on page 72 . refer to the individual module sections for a full description of the alter- nate functions. c pin logic r pu see figure "general digital i/o" for details pxn
68 7799d?avr?11/10 atmega8u2/16u2/32u2 note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital i/o. 12.2 ports as general digital i/o the ports are bi-directional i/o ports with optional internal pull-ups. figure 12-2 shows a func- tional description of one i/o-port pin, here generically called pxn. figure 12-2. general digital i/o (1) note: 1. wrx, wpx, wdx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. 12.2.1 configuring the pin each port pin consists of three register bits: ddxn, portxn, and pinxn. as shown in ?register description for i/o-ports? on page 82 , the ddxn bits are accessed at the ddrx i/o address, the portxn bits at the portx i/o address, and the pinxn bits at the pinx i/o address. the ddxn bit in the ddrx register selects the direction of this pin. if ddxn is written logic one, pxn is configured as an output pin. if ddxn is written logic zero, pxn is configured as an input pin. if portxn is written logic one when the pin is configured as an input pin, the pull-up resistor is activated. to switch the pull-up resistor off, portxn has to be written logic zero or the pin has to be configured as an output pin. the port pins are tri-stated when reset condition becomes active, even if no clocks are running. clk rpx rrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q reset reset q q d q q d clr portxn q q d clr ddxn pinxn dat a bus sleep sleep: sleep control pxn i/o wpx 0 1 wrx wpx: write pinx register
69 7799d?avr?11/10 atmega8u2/16u2/32u2 if portxn is written logic one when the pin is configured as an output pin, the port pin is driven high (one). if portxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero). 12.2.2 toggling the pin writing a logic one to pinxn toggles the value of portxn, independent on the value of ddrxn. note that the sbi instruction can be used to toggle one single bit in a port. 12.2.3 switching between input and output when switching between tri-state ({ddxn, portxn} = 0b00) and output high ({ddxn, portxn} = 0b11), an intermediate state with either pull-up enabled {ddxn, portxn} = 0b01) or output low ({ddxn, portxn} = 0b10) occurs. normally, the pull-up enabled state is fully acceptable, as a high-impedant environment will not notice the difference between a strong high driver and a pull-up. if this is not the case, the pud bit in the mcucr register can be set to disable all pull- ups in all ports. switching between input with pull-up and output low generates the same problem. the user must use either the tri-state ({ddxn, portxn} = 0b00) or the output high state ({ddxn, portxn} = 0b11) as an intermediate step. table 12-1 summarizes the control signals for the pin value. 12.2.4 reading the pin value independent of the setting of data direction bit ddxn, the port pin can be read through the pinxn register bit. as shown in figure 12-2 , the pinxn register bit and the preceding latch con- stitute a synchronizer. this is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. figure 12-3 shows a timing dia- gram of the synchronization when reading an externally applied pin value. the maximum and minimum propagation delays are denoted t pd,max and t pd,min respectively. table 12-1. port pin configurations ddxn portxn pud (in mcucr) i/o pull-up comment 0 0 x input no tri-state (hi-z) 0 1 0 input yes pxn will source current if ext. pulled low. 0 1 1 input no tri-state (hi-z) 1 0 x output no output low (sink) 1 1 x output no output high (source)
70 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 12-3. synchronization when reading an externally applied pin value consider the clock period starting shortly after the first falling edge of the system clock. the latch is closed when the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of the ?sync latch? signal. the signal value is latched when the system clock goes low. it is clocked into the pinxn register at the succeeding positive clock edge. as indi- cated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed between ? and 1? system clock period depending upon the time of assertion. when reading back a software assigned pin value, a nop instruction must be inserted as indi- cated in figure 12-4 . the out instruction sets the ?sync latch? signal at the positive edge of the clock. in this case, the delay tpd through the synchronizer is 1 system clock period. figure 12-4. synchronization when reading a software assigned pin value the following code example shows how to set port b pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. the resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. xxx in r17, pinx 0x00 0xff instructions sync latch pinxn r17 xxx system clk t pd, max t pd, min out portx, r16 nop in r17, pinx 0xff 0x00 0xff system clk r16 instructions sync latch pinxn r17 t pd
71 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. for the assembly program, two temporary registers are used to minimize the time from pull- ups are set on pins 0, 1, 6, and 7, until the direction bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as strong high drivers. 12.2.5 digital input enable and sleep modes as shown in figure 12-2 , the digital input signal can be clamped to ground at the input of the schmitt-trigger. the signal denoted sleep in the figure, is set by the mcu sleep controller in power-down mode, power-save mode, and standby mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to v cc /2. sleep is overridden for port pins enabled as external interrupt pins. if the external interrupt request is not enabled, sleep is active also for these pins. sleep is also overridden by various other alternate functions as described in ?alternate port functions? on page 72 . if a logic high level (?one?) is present on an asynchronous external interrupt pin configured as ?interrupt on rising edge, falling edge, or any logic change on pin? while the external interrupt is not enabled, the corresponding external interrupt flag will be set when resuming from the above mentioned sleep mode, as the clamping in these sleep mode produces the requested logic change. assembly code example (1) ... ; define pull-ups and set outputs high ; define directions for port pins ldi r16,(1< 72 7799d?avr?11/10 atmega8u2/16u2/32u2 12.2.6 unconnected pins if some pins are unused, it is recommended to ensure that these pins have a defined level. even though most of the digital inputs are disabled in the deep sleep modes as described above, float- ing inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (reset, active mode and idle mode). the simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. in this case, the pull-up will be disabled during reset. if low power consumption during reset is important, it is recommended to use an external pull-up or pull-down. connecting unused pins directly to v cc or gnd is not recommended, since this may cause excessive currents if the pin is accidentally configured as an output. 12.3 alternate port functions most port pins have alternate functions in addition to being general digital i/os. figure 12-5 shows how the port pin control signals from the simplified figure 12-2 can be overridden by alternate functions. the overriding signals may not be present in all port pins, but the figure serves as a generic description applicable to all port pins in the avr microcontroller family. figure 12-5. alternate port functions (1) clk rpx rrx wrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q set clr 0 1 0 1 0 1 dixn aioxn dieoexn pvovxn pvoexn ddovxn ddoexn puoexn puovxn puoexn: pxn pull-up override enable puovxn: pxn pull-up override value ddoexn: pxn data direction override enable ddovxn: pxn data direction override value pvoexn: pxn port value override enable pvovxn: pxn port value override value dixn: digital input pin n on portx aioxn: analog input/output pin n on portx reset reset q q d clr q q d clr q q d clr pinxn portxn ddxn data b u s 0 1 dieovxn sleep dieoexn: pxn digital input-enable override enable dieovxn: pxn digital input-enable override value sleep: sleep control pxn i/o 0 1 ptoexn ptoexn: pxn, port toggle override enable wpx: write pinx wpx
73 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. wrx, wpx, wdx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. all other signals are unique for each pin. table 12-2 summarizes the function of the overriding signals. the pin and port indexes from fig- ure 12-5 are not shown in the succeeding tables. the overriding signals are generated internally in the modules having the alternate function. the following subsections shortly describe the alternate functions for each port, and relate the overriding signals to the alternate function. refer to the alternate function description for further details. table 12-2. generic description of overriding signals for alternate functions signal name full name description puoe pull-up override enable if this signal is set, the pull-up enable is controlled by the puov signal. if this signal is cleared, the pull-up is enabled when {ddxn, portxn, pud} = 0b010. puov pull-up override value if puoe is set, the pull-up is enabled/disabled when puov is set/cleared, regardless of the setting of the ddxn, portxn, and pud register bits. ddoe data direction override enable if this signal is set, the output driver enable is controlled by the ddov signal. if this signal is cleared, the output driver is enabled by the ddxn register bit. ddov data direction override value if ddoe is set, the output driver is enabled/disabled when ddov is set/cleared, regardless of the setting of the ddxn register bit. pvoe port value override enable if this signal is set and the output driver is enabled, the port value is controlled by the pvov signal. if pvoe is cleared, and the output driver is enabled, the port value is controlled by the portxn register bit. pvov port value override value if pvoe is set, the port value is set to pvov, regardless of the setting of the portxn register bit. ptoe port toggle override enable if ptoe is set, the portxn register bit is inverted. dieoe digital input enable override enable if this bit is set, the digital input enable is controlled by the dieov signal. if this signal is cleared, the digital input enable is determined by mcu state (normal mode, sleep mode). dieov digital input enable override value if dieoe is set, the digital input is enabled/disabled when dieov is set/cleared, regardless of the mcu state (normal mode, sleep mode). di digital input this is the digital input to alternate functions. in the figure, the signal is connected to the output of the schmitt trigger but before the synchronizer. unless the digital input is used as a clock source, the module with the alternate function will use its own synchronizer. aio analog input/output this is the analog input/output to/from alternate functions. the signal is connected directly to the pad, and can be used bi- directionally.
74 7799d?avr?11/10 atmega8u2/16u2/32u2 12.3.1 alternate functions of port b the port b pins with alternate functions are shown in table 12-3 . the alternate pin configuration is as follows: ? oc0a/oc1c/pcint7, bit 7 oc0a, output compare match a output: the pb7 pin can serve as an external output for the timer/counter0 output compare. the pin has to be configured as an output (ddb7 set ?one?) to serve this function. the oc0a pin is also the output pin for the pwm mode timer function. oc1c, output compare match c output: the pb7 pin can serve as an external output for the timer/counter1 output compare c. the pin has to be configured as an output (ddb7 set ?one?) to serve this function. the oc1c pin is also the output pin for the pwm mode timer function. pcint7, pin change interrupt source 7: the pb7 pin can serve as an external interrupt source. ? pcint6, bit 6 pcint6, pin change interrupt source 6: the pb6 pin can serve as an external interrupt source. ? pcint5, bit 5 pcint5, pin change interrupt source 5: the pb5 pin can serve as an external interrupt source. ? t1/pcint4, bit 4 t1, timer/counter1 counter source. pcint4, pin change interrupt source 4: the pb4 pin can serve as an external interrupt source. ? pdo/miso/pcint3 ? port b, bit 3 pdo, spi serial programming data output. during serial program downloading, this pin is used as data output line for the at90usb82/162. miso: master data input, slave data output pin for spi channel. when the spi is enabled as a master, this pin is configured as an input regardless of the setting of ddb3. when the spi is enabled as a slave, the data direction of this pin is controlled by ddb3. when the pin is forced to be an input, the pull-up can still be controlled by the portb3 bit. pcint3, pin change interrupt source 3: the pb3 pin can serve as an external interrupt source. table 12-3. port b pins alternate functions port pin alternate functions pb7 oc0a/oc1c/pcint7 (output compare and pwm output a for timer/counter0, output compare and pwm output c for timer/counter1 or pin change interrupt 7) pb6 pcint6 (pin change interrupt 6) pb5 pcint5 (pin change interrupt 5) pb4 t1/pcint4 (timer/counter1 clock input or pin change interrupt 4) pb3 pdo/miso/pcint3 (programming data output or spi bus master input/slave output or pin change interrupt 3) pb2 pdi/mosi/pcint2 (programming data input or spi bus master output/slave input or pin change interrupt 2) pb1 sclk/pcint1 (spi bus serial clock or pin change interrupt 1) pb0 ss/pcint0 (spi slave select input or pin change interrupt 0)
75 7799d?avr?11/10 atmega8u2/16u2/32u2 ? pdi/mosi/pcint2 ? port b, bit 2 pdi, spi serial programming data input. during serial program downloading, this pin is used as data input line for the at90usb82/162. mosi: spi master data output, slave data input for spi channel. when the spi is enabled as a slave, this pin is configured as an input regardless of the setting of ddb2. when the spi is enabled as a master, the data direction of this pin is controlled by ddb2. when the pin is forced to be an input, the pull-up can still be controlled by the portb2 bit. pcint2, pin change interrupt source 2: the pb2 pin can serve as an external interrupt source. ? sck/pcint1 ? port b, bit 1 sck: master clock output, slave clock input pin for spi channel. when the spi is enabled as a slave, this pin is configured as an input regardless of the setting of ddb1. when the spi0 is enabled as a master, the data direction of this pin is controlled by ddb1. when the pin is forced to be an input, the pull-up can still be controlled by the portb1 bit. this pin also serves as clock for the serial programming interface. pcint1, pin change interrupt source 1: the pb1 pin can serve as an external interrupt source. ? ss/pcint0 ? port b, bit 0 s s: slave port select input. when the spi is enabled as a slave, this pin is configured as an input regardless of the setting of ddb0. as a slave, the spi is activated when this pin is driven low. when the spi is enabled as a master, the data direction of this pin is controlled by ddb0. when the pin is forced to be an input, the pull-up can still be controlled by the portb0 bit. pcint0, pin change interrupt source 0: the pb0 pin can serve as an external interrupt source. table 12-4 and table 12-5 relate the alternate functions of port b to the overriding signals shown in figure 12-5 on page 72 . spi mstr input and spi slave output constitute the miso signal, while mosi is divided into spi mstr output and spi slave input. pcint0, pin change interrupt source 0: the pb0 pin can serve as an external interrupt source
76 7799d?avr?11/10 atmega8u2/16u2/32u2 . table 12-4 and table 12-5 relate the alternate functions of port b to the overriding signals shown in figure 12-5 on page 72 . spi mstr input and spi slave output constitute the miso signal, while mosi is divided into spi mstr output and spi slave input.. table 12-4. overriding signals for alternate functions in pb7..pb4 signal name pb7/oc0a/oc1c/ pcint7 pb6/pcint6 pb5/pcint5 pb4/t1/pcint4 puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe oc0a/oc1c enable 0 0 0 pvov oc0a/oc1c 0 0 0 dieoe pcint7 ? pcie0 pcint6 ? pcie0 pcint5 ? pcie0 pcint4 ? pcie0 dieov 1 1 1 1 di pcint7 input pcint6 input pcint5 input pcint4 input t1 input aio ? ? ? ? table 12-5. overriding signals for alternate functions in pb3..pb0 signal name pb3/miso/pcint3/ pdo pb2/mosi/pcint2/ pdi pb1/sck/ pcint1 pb0/ ss/pcint0 puoe spe ? mstr spe ? mstr spe ? mstr spe ? mstr puov portb3 ? pud portb2 ? pud portb1 ? pud portb0 ? pud ddoe spe ? mstr spe ? mstr spe ? mstr spe ? mstr ddov 0 0 0 0 pvoe spe ? mstr spe ? mstr spe ? mstr 0 pvov spi slave output spi mstr output sck output 0 dieoe pcint3 ? pcie0 pcint2 ? pcie0 pcint1 ? pcie0 pcint0 ? pcie0 dieov 1 1 1 1 di spi mstr input pcint3 input spi slave input pcint2 input sck input pcint1 input spi ss pcint0 input aio ? ? ? ?
77 7799d?avr?11/10 atmega8u2/16u2/32u2 12.3.2 alternate functions of port c the port c alternate function is as follows: the alternate pin configuration is as follows: ? icp1/int4/clk0, bit 7 icp1, input capture pin 1 :the pc7 pin can act as an input capture for timer/counter1. int4, external interrupt source 4 : the pc7 pin can serve as an external interrupt source to the mcu. clk0, clock output : the pc7 pin can serve as oscillator clock ouput if the feature is enabled by fuse. ? pcint8/oc1a, bit 6 pcint8, pin change interrupt source 8 : the pc6 pin can serve as an external interrupt source. oc1a, output compare match a output: the pc6 pin can serve as an external output for the timer/counter1 output compare. the pin has to be configured as an output (ddc6 set ?one?) to serve this function. the oc1a pin is also the output pin for the pwm mode timer function. ? pcint9/oc1b, bit 5 pcint9, pin change interrupt source 9: the pc5 pin can serve as an external interrupt source. oc1b, output compare match b output: the pc5 pin can serve as an external output for the timer/counter1 output compare. the pin has to be configured as an output (ddc5 set ?one?) to serve this function. the oc1b pin is also the output pin for the pwm mode timer function. ? pcint10, bit 4 pcint10, pin change interrupt source 10 : the pc4 pin can serve as an external interrupt source. ? pcint11, bit 2 pcint11, pin change interrupt source 11 : the pc2 pin can serve as an external interrupt source. ? reset/dw, bit 1 table 12-6. port c pins alternate functions port pin alternate function pc7 icp1/int4/clko pc6 pcint8/oc1a pc5 pcint9/oc1b pc4 pcint10 -- pc2 pcint11 pc1 reset, dw pc0 xtal2
78 7799d?avr?11/10 atmega8u2/16u2/32u2 r e s e t, reset input. external reset input is active low and enabled by unprogramming ("1") the rstdisbl fuse. pullup is activated and output driver and digital input are deactivated when the pin is used as the reset pin. dw, debugwire channel. when the debugwire enable (dwen) fuse is programmed and lock bits are unprogrammed, the debugwire system within the target device is activated. the reset port pin is configured as a wired -and (open-drain) bi-directional i/o pin with pull-up enabled and becomes the communication gateway between the target and the emulator. ? xt al2, bit 0 xtal2, oscillator. the pc0 pin can serve as inverting output for internal oscillator amplifier. table 12-7 and table 12-8 relate the alternate functions of port c to the overriding signals shown in figure 12-5 on page 72 . table 12-7. overriding signals for alternate functions in pc7..pc4 signal name pc7/icp1/int4/clk0 pc6/pcint8/ oc1a pc5/pcint9/ oc1b pc4/pcint10 puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe 0 oc1a enable oc1b enable 0 pvov 0 oc1a oc1b 0 dieoe int4 enable pcint8 enable pcint9 enable pcint10 enable dieov 1 1 1 1 di int4 input pcint8 input pcint9 input pcint10 input aio ? ? ? ? table 12-8. overriding signals for alternate functions in pc2..pc0 signal name pc2/pcint11 pc1/ reset/dw pc0/xtal2 puoe 0 0 0 puov 0 0 0 ddoe 0 0 0 ddov 0 0 0 pvoe 0 0 0 pvov 0 0 0 dieoe pcint11 enable 0 0 dieov 1 0 0 di pcint11 input ? ? aio ? ? ?
79 7799d?avr?11/10 atmega8u2/16u2/32u2 12.3.3 alternate functions of port d the port d pins with alternate functions are shown in table 12-9 . the alternate pin configuration is as follows: ? hwb/to/int7/ cts , bit 7 hwb, hardware boot : the pd7 pin can serve as to, timer/counter0 counter source. int7, external interrupt source 7: the pd7 pin can serve as an external interrupt source to the mcu. c t s, usart1 transmitter flow control. this pin can control the transmitter in function of its state. ? int6/ rts ,bit 6 int6, external interrupt source 6: the pd6 pin can serve as an external interrupt source to the mcu. rts, usart1 receiver flow control. this pin can control the receiver in function of its state. ? xck1/pcint12 , bit 5 xck1, usart1 external clock : the data direction register ddrd5 controls whether the clock is output (ddrd5 set) or input (ddrd5 cleared). the xck1 pin is active only when the usart1 operates in synchronous mode. pcint12, pin change interrupt source 12: the pd5 pin can serve as an external interrupt source. ? int5 , bit 4 int5, external interrupt source 5: the pd4 pin can serve as an external interrupt source to the mcu. ? int3/txd1 , bit 3 int3, external interrupt source 3: the pd3 pin can serve as an external interrupt source to the mcu. table 12-9. port d pins alternate functions port pin alternate function pd7 hwb/to/int7/ cts pd6 int6/ r ts pd5 xck1/pcint12 (usart1 external clock input/output) pd4 int5 pd3 int3/txd1 (external interrupt3 input or usart1 transmit pin) pd2 int2/ain1/rxd1(external interrupt2 input or usart1 receive pin) pd1 int1/ain0 (external interrupt1 input) pd0 int0/oc0b (external interrupt0 input)
80 7799d?avr?11/10 atmega8u2/16u2/32u2 txd1, usart1 transmit data : when the usart1 transmitter is enabled, this pin is config- ured as an ouput regardless of ddrd3. ? int2/ain1/rxd1 , bit 2 int2, external interrupt source 2: the pd2 pin can serve as an external interrupt source to the mcu. ain1, analog comparator negative input. this pin is directly connected to the negative input of the analog comparator. rxd1, usart1 receive data : when the usart1 receiver is enabled, t his pin is configured as an input regardless of ddrd2. when the usart forces this pin to be an input, the pull-up can still be controlled by the portd2 bit. ? int1/ain0 , bit 1 int1, external interrupt source 1: the pd1 pin can serve as an external interrupt source to the mcu. ain0, analog comparator positive input. this pin is directly connected to the positive input of the analog comparator. ? int0/oc0b , bit 0 int0, external interrupt source 0: the pd0 pin can serve as an external interrupt source to the mcu. oc0b, output compare match b output: the pd0 pin can serve as an external output for the timer/counter0 output compare. the pin has to be configured as an output (ddd0 set ?one?) to serve this function. the oc0b pin is also the output pin for the pwm mode timer function. table 12-10 and table 12-11 relates the alternate functions of port d to the overriding signals shown in figure 12-5 on page 72 .
81 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. when enabled, the 2-wire serial interface enables slew-rate controls on the output pins pd0 and pd1. this is not shown in this table. in addition, spike filters are connected between the aio outputs shown in the port figure. table 12-10. overriding signals for alternate functions pd7..pd4 signal name pd7/t0/int7/ hbw/ cts pd6/int6/ rts pd5/xck/pcint12 pd4/int5 puoe cts rts 0 0 puov portd7 ? pud 00 0 ddoe cts rts 0 0 ddov 0 1 0 0 pvoe 0 r ts output enable xck output enable 0 pvov 0 r ts output xck1 output 0 dieoe int7/ cts enable int6 enable pcint12 enable int5 enable dieov 1 1 1 1 di t0 input int7 input cts input int6 input xck input pcint12 input int5 input aio ? ? ? ? table 12-11. overriding signals for alternate functions in pd3..pd0 (1) signal name pd3/int3/txd1 pd2/int2/rxd1/ ain1 pd1/int1/ain0 pd0/int0/oc0b puoe txen1 rxen1 0 0 puov 0 portd2 ? pud 0 0 ddoe txen1 rxen1 0 0 ddov 1 0 0 0 pvoe txen1 0 0 oc0b enable pvov txd1 0 0 oc0b dieoe int3 enable int2 enable ain1 enable int1 enable ain0 enable int0 enable dieov 1 ain1 enable ain0 enable 1 di int3 input int2 input/rxd1 int1 input int0 input aio ? ain1 input ain0 input ?
82 7799d?avr?11/10 atmega8u2/16u2/32u2 12.4 register description for i/o-ports 12.4.1 mcucr ? mcu control register ? bit 4 ? pud: pull-up disable when this bit is written to one, the pull-ups in the i/o ports are disabled even if the ddxn and portxn registers are configured to enable the pull-ups ({ddxn, portxn} = 0b01). see ?con- figuring the pin? on page 68 for more details about this feature. 12.4.2 portb ? port b data register 12.4.3 ddrb ? port b data direction register 12.4.4 pinb ? port b input pins address 12.4.5 portc ? port c data register 12.4.6 ddrc ? port c data direction register 12.4.7 pinc ? port c input pins address bit 7 6 5 4 3 2 1 0 0x35 (0x55) jtd ? ? pud ? ? ivsel ivce mcucr read/write r/w r r r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x05 (0x25) portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 portb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x04 (0x24) ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 ddrb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x03 (0x23) pinb7 pinb6 pinb5 pinb4 pinb3 pinb2 pinb1 pinb0 pinb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 0x08 (0x28) portc7 portc6 portc5 portc4 - portc2 portc1 portc0 portc read/write r/w r/w r/w r/w r r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x07 (0x27) ddc7 ddc6 ddc5 ddc4 - ddc2 ddc1 ddc0 ddrc read/write r/w r/w r/w r/w r r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x06 (0x26) pinc7 pinc6 pinc5 pinc4 - pinc2 pinc1 pinc0 pinc read/write r/w r/w r/w r/w r r/w r/w r/w initial value n/a n/a n/a n/a n/a n/a n/a n/a
83 7799d?avr?11/10 atmega8u2/16u2/32u2 12.4.8 portd ? port d data register 12.4.9 ddrd ? port d data direction register 12.4.10 pind ? port d input pins address bit 76543210 0x0b (0x2b) portd7 portd6 portd5 portd4 portd3 portd2 portd1 portd0 portd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x0a (0x2a) ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 ddrd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x09 (0x29) pind7 pind6 pind5 pind4 pind3 pind2 pind1 pind0 pind read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value n/a n/a n/a n/a n/a n/a n/a n/a
84 7799d?avr?11/10 atmega8u2/16u2/32u2 13. external interrupts 13.1 overview the external interrupts are triggered by the int[7:0] pin or any of the pcint[12:0] pins. observe that, if enabled, the interrupts will trigger even if the int[7:0] or pcint[12:0] pins are configured as outputs. this feature provides a way of generating a software interrupt. the pin change interrupt pci0 will trigger if any enabled pcint[7:0] pin toggles. pcmsk0 reg- ister control which pins contribute to the pin change interrupts. the pin change interrupt pci1 will trigger if any enabled pcint[12:8] pin toggles. pcmsk1 register control which pins contrib- ute to the pin change interrupts. pin change interrupts on pcint[12:0] are detected asynchronously. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the external interrupts can be triggered by a falling or rising edge or a low level. this is set up as indicated in the specification for the externa l interrupt control registers ? eicra (int[3:0]) and eicrb (int[7:4]). when the external interrupt is enabled and is configured as level trig- gered, the interrupt will trigger as long as the pin is held low. note that recognition of falling or rising edge interrupts on int[7:4] requires the presence of an i/o clock, described in ?system clock and clock options? on page 26 . low level interrupts and the edge interrupt on int[3:0] are detected asynchronously. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the i/o clock is halted in all sleep modes except idle mode. note that if a level triggered interrupt is used for wake-up from power-down, the required level must be held long enough for the mcu to complete the wake-up to trigger the level interrupt. if the level disappears before the end of the start-up time, the mcu will still wake up, but no inter- rupt will be generated. the start-up time is defined by the sut and cksel fuses as described in ?system clock and clock options? on page 26 . 13.2 register description 13.2.1 eicra ? external interrupt control register a the external interrupt control register a contains control bits for interrupt sense control. ? bits 7:0 ? isc31, isc30 ? isc00, isc00: external interrupt 3:0 sense control bits the external interrupts 3:0 are activated by the external pins int[3:0] if the sreg i-flag and the corresponding interrupt mask in the eimsk is set. the level and edges on the external pins that activate the interrupts are defined in table 13-1 . edges on int[3:0] are registered asynchro- nously. pulses on int[3:0] pins wider than the minimum pulse width given in ?external interrupts characteristics? on page 268 will generate an interrupt. shorter pulses are not guaranteed to generate an interrupt. if low level interrupt is selected, the low level must be held until the com- pletion of the currently executing instruction to generate an interrupt. if enabled, a level triggered interrupt will generate an interrupt request as long as the pin is held low. when changing the iscn bit, an interrupt can occur. therefore, it is recommended to first disable intn by clearing its interrupt enable bit in the eimsk register. then, the iscn bit can be changed. finally, the intn bit 76543210 (0x69) isc31 isc30 isc21 isc20 isc11 isc10 isc01 isc00 eicra read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
85 7799d?avr?11/10 atmega8u2/16u2/32u2 interrupt flag should be cleared by writing a logical one to its interrupt flag bit (intfn) in the eifr register before the interrupt is re-enabled. note: 1. n = 3, 2, 1or 0. when changing the iscn1/iscn0 bits, the interrupt must be disabled by clearing its interrupt enable bit in the eimsk register. otherwise an interrupt can occur when the bits are changed. 13.2.2 eicrb ? external interrupt control register b ? bits 7:0 ? isc71, isc70 - isc41, isc40: external interrupt 7:4 sense control bits the external interrupts [7:4] are activated by the external pins int[7:4] if the sreg i-flag and the corresponding interrupt mask in the eimsk is set. the level and edges on the external pins that activate the interrupts are defined in table 13-2 . the value on the int[7:4] pins are sampled before detecting edges. if edge or toggle interrupt is selected, pu lses that last longer than one clock period will generate an interrupt. shorter pulses are not guaranteed to generate an inter- rupt. observe that cpu clock frequency can be lower than the xtal frequency if the xtal divider is enabled. if low level interrupt is selected, the low level must be held until the comple- tion of the currently executing instruction to generate an interrupt. if enabled, a level triggered interrupt will generate an interrupt request as long as the pin is held low. note: 1. n = 7, 6, 5 or 4. when changing the iscn1/iscn0 bits, the interrupt must be disabled by clearing its interrupt enable bit in the eimsk register. otherwise an interrupt can occur when the bits are changed. table 13-1. interrupt sense control (1) iscn1 iscn0 description 0 0 the low level of intn generates an interrupt request. 0 1 any edge of intn generates asynchronously an interrupt request. 1 0 the falling edge of intn generates asynchronously an interrupt request. 1 1 the rising edge of intn generates asynchronously an interrupt request. bit 76543210 (0x6a) isc71 isc70 isc61 isc60 isc51 isc50 isc41 isc40 eicrb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 13-2. interrupt sense control (1) iscn1 iscn0 description 0 0 the low level of intn generates an interrupt request. 0 1 any logical change on intn generates an interrupt request 1 0 the falling edge between two samples of intn generates an interrupt request. 1 1 the rising edge between two samples of intn generates an interrupt request.
86 7799d?avr?11/10 atmega8u2/16u2/32u2 13.2.3 eimsk ? external interrupt mask register ? bits 7:0 ? int[7:0]: external interrupt request 7:0 enable when an int[7:0] bit is written to one and the i-bit in the status register (sreg) is set (one), the corresponding external pin interrupt is enabled. the interrupt sense control bits in the external interrupt control registers ? eicra and eicrb ? defines whether the external interrupt is acti- vated on rising or falling edge or level sensed. activity on any of these pins will trigger an interrupt request even if the pin is enabled as an output. this provides a way of generating a software interrupt. 13.2.4 eifr ? external interrupt flag register ? bits 7:0 ? intf[7:0]: external interrupt flags 7:0 when an edge or logic change on the int[7:0] pin triggers an interrupt request, intf[7:0] becomes set (one). if the i-bit in sreg and the corresponding interrupt enable bit, int[7:0] in eimsk, are set (one), the mcu will jump to the interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the f lag can be cleared by writing a logical one to it. these flags are always cleared when int[7:0] are configured as level interrupt. note that when entering sleep mode with the int[3:0] interrupts disabled, the input buffers on these pins will be disabled. this may cause a logic change in internal signals which will set the intf[3:0] flags. see ?digital input enable and sleep modes? on page 71 for more information. 13.2.5 pcicr ? pin change interrupt control register ? bit 1:0 ? pcie[1:0]: pin change interrupt enable 1:0 when the pcie1/0 bit is set (one) and the i-bit in the status register (sreg) is set (one), pin change interrupt 1/0 is enabled. any change on any enabled pcint[12:8]/[7:0] pin will cause an interrupt. the corresponding interrupt of pin change interrupt request is executed from the pci1/0 interrupt vector. pcint[12:8]/[7:0] pins are enabled individually by the pcmsk1/0 register. 13.2.6 pcifr ? pin change interrupt flag register bit 76543210 0x1d (0x3d) int7 int6 int5 int4 int3 int2 int1 iint0 eimsk read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x1c (0x3c) intf7 intf6 intf5 intf4 intf3 intf2 intf1 intf0 eifr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x68) - - ? ? ? ? pcie1 pcie0 pcicr read/write r r r r r r r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x1b (0x3b) - - ? ? ? ? pcif1 pcif0 pcifr read/write r r r r r r r/w r/w initial value 0 0 0 0 0 0 0 0
87 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 1:0 ? pcif[1:0]: pin change interrupt flag 1:0 when a logic change on any pcint[12:8]/[7:0] pin triggers an interrupt request, pcif1/0 becomes set (one). if the i-bit in sreg and the pcie1/0 bit in eimsk are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is exe- cuted. alternatively, the flag can be cleared by writing a logical one to it. 13.2.7 pcmsk0 ? pin change mask register 0 ? bit 7:0 ? pcint[7:0]: pin change enable mask 7:0 each pcint[7:0] bit selects whether pin change interrupt is enabled on the corresponding i/o pin. if pcint[7:0] is set and the pcie0 bit in pcicr is set, pin change interrupt is enabled on the corresponding i/o pin. if pcint[7:0] is cleared, pin change interrupt on the corresponding i/o pin is disabled. 13.2.8 pcmsk1 ? pin change mask register 1 ? bit 4:0 ? pcint[12:8]: pin change enable mask 12:8 each pcint[12:8] bit selects whether pin change interrupt is enabled on the corresponding i/o pin. if pcint[12:8] is set and the pcie1 bit in pc icr is set, pin change interrupt is enabled on the corresponding i/o pin. if pcint[12:8] is cleared, pin change interrupt on the corresponding i/o pin is disabled. bit 76543210 (0x6b) pcint7 pcint6 pcint5 pcint4 pcint3 pcint2 pcint1 pcint0 pcmsk0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0000 bit 76543210 (0x6c) - - - pcint12 pcint11 pcint10 pcint9 pcint8 pcmsk1 read/write r r r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0000
88 7799d?avr?11/10 atmega8u2/16u2/32u2 14. timer/counter0 and timer/counter1 prescalers 14.1 overview timer/counter0 and 1 share the same prescaler module, but the timer/counters can have dif- ferent prescaler settings. the description below applies to all timer/counters. tn is used as a general name, n = 0 or 1. 14.2 internal clock source the timer/counter can be clocked directly by the system clock (by setting the csn[2:0] = 1). this provides the fastest operation, with a maximum timer/counter clock frequency equal to system clock frequency (f clk_i/o ). alternatively, one of four taps from the prescaler can be used as a clock source. the prescaled clock has a frequency of either f clk_i/o /8, f clk_i/o /64, f clk_i/o /256, or f clk_i/o /1024. 14.3 prescaler reset the prescaler is free running, i.e., operates independently of the clock select logic of the timer/counter, and it is shared by the timer/counter tn. since the prescaler is not affected by the timer/counter?s clock select, the state of the prescaler will have implications for situations where a prescaled clock is used. one example of prescaling artifacts occurs when the timer is enabled and clocked by the prescaler (6 > csn[2:0] > 1). the number of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to n+1 system clock cycles, where n equals the prescaler divisor (8, 64, 256, or 1024). it is possible to use the prescaler reset for synchronizing the timer/counter to program execu- tion. however, care must be taken if the other timer/counter that shares the same prescaler also uses prescaling. a prescaler reset will affect the prescaler period for all timer/counters it is connected to. 14.4 external clock source an external clock source applied to the tn pin can be used as timer/counter clock (clk tn ). the tn pin is sampled once every system clock cycle by the pin synchronization logic. the synchro- nized (sampled) signal is then passed through the edge detector. figure 14-1 shows a functional equivalent block diagram of the tn synchronization and edge detector logic. the registers are clocked at the positive edge of the internal system clock ( clk i/o ). the latch is transparent in the high period of the internal system clock. the edge detector generates one clk tn pulse for each positive (csn2:0 = 7) or negative (csn2:0 = 6) edge it detects. figure 14-1. tn/t0 pin sampling tn_sync (to clock select logic) edge detector synchronization dq dq le dq tn clk i/o
89 7799d?avr?11/10 atmega8u2/16u2/32u2 the synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles from an edge has been applied to the tn pin to the counter is updated. enabling and disabling of the clock input must be done when tn has been stable for at least one system clock cycle, otherwise it is a risk that a false timer/counter clock pulse is generated. each half period of the external clock applied must be longer than one system clock cycle to ensure correct sampling. the external clock must be guaranteed to have less than half the sys- tem clock frequency (f extclk < f clk_i/o /2) given a 50/50% duty cycle. since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling fre- quency (nyquist sampling theorem). however, due to variation of the system clock frequency and duty cycle caused by oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than f clk_i/o /2.5. an external clock source can not be prescaled. figure 14-2. prescaler for synchronous timer/counters 14.5 register description 14.5.1 gtccr ? general timer/counter control register ? bit 7 ? tsm: timer/counter synchronization mode writing the tsm bit to one activates the timer/counter synchronization mode. in this mode, the value that is written to the psrasy and psrsync bits is kept, hence keeping the correspond- ing prescaler reset signals asserted. this ensures that the corresponding timer/counters are halted and can be configured to the same value without the risk of one of them advancing during configuration. when the tsm bit is written to zero, the psrasy and psrsync bits are cleared by hardware, and the timer/counters start counting simultaneously. psr10 clear tn tn clk i/o synchronization synchronization timer/countern clock source clk tn timer/countern clock source clk tn csn0 csn1 csn2 csn0 csn1 csn2 bit 7 6 5 4 3 2 1 0 0x23 (0x43) tsm ? ? ? ? ? - psrsync gtccr read/write r/w r r r r r r r/w initial value 0 0 0 0 0 0 0 0
90 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bits 6:1 ? res: reserved these bits are reserved and will always read as zero. ? bit 0 ? psrsync: prescaler reset for synchronous timer/counters when this bit is one, timer/counter0 and timer/counter1, timer/counter3, timer/counter4 and timer/counter5 prescaler will be reset. this bit is normally cleared immediately by hardware, except if the tsm bit is set. note that timer/counter0 and timer/counter1 share the same pres- caler and a reset of this prescaler will affect all timers.
91 7799d?avr?11/10 atmega8u2/16u2/32u2 15. 8-bit timer/counter0 with pwm 15.1 features ? two independent output compare units ? double buffered output compare registers ? clear timer on compare match (auto reload) ? glitch free, phase correct pulse width modulator (pwm) ? variable pwm period ? frequency generator ? three independent interrupt sources (tov0, ocf0a, and ocf0b) 15.2 overview timer/counter0 is a general purpose 8-bit timer/counter module, with two independent output compare units, and with pwm support. it allows accurate program execution timing (event man- agement) and wave generation. a simplified block diagram of the 8-bit timer/counter is shown in figure 15-1 . for the actual placement of i/o pins, refer to ?pinout? on page 2 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the device-specific i/o register and bit locations are listed in the ?register description? on page 102 . figure 15-1. 8-bit timer/counter block diagram 15.2.1 registers the timer/counter (tcnt0) and output compare registers (ocr0a and ocr0b) are 8-bit registers. interrupt request (abbreviated to int.req. in the figure) signals are all visible in the timer interrupt flag register (tifr0). all interrupts are individually masked with the timer inter- rupt mask register (timsk0). tifr0 and timsk0 are not shown in the figure. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the t0 pin. the clock select logic block controls which clock source and edge the timer/counter clock select timer/counter data bus ocrna ocrnb = = tcntn waveform generation waveform generation ocna ocnb = fixed top value control logic = 0 top bottom count clear direction tovn (int.req.) ocna (int.req.) ocnb (int.req.) tccrna tccrnb tn edge detector ( from prescaler ) clk tn
92 7799d?avr?11/10 atmega8u2/16u2/32u2 uses to increment (or decrement) its value. the timer/counter is inactive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t0 ). the double buffered output compare registers (ocr0a and ocr0b) are compared with the timer/counter value at all times. the result of the compare can be used by the waveform gen- erator to generate a pwm or variable frequency output on the output compare pins (oc0a and oc0b). see ?output compare unit? on page 93. for details. the compare match event will also set the compare flag (ocf0a or ocf0b) which ca n be used to generate an output compare interrupt request. 15.2.2 definitions many register and bit references in this section are written in general form. a lower case ?n? replaces the timer/counter number, in this case 0. a lower case ?x? replaces the output com- pare unit, in this case compare unit a or compare unit b. however, when using the register or bit defines in a program, the precise form must be used, i.e., tcnt0 for accessing timer/counter0 counter value and so on. the definitions in table 15-1 are also used extensively throughout the document. 15.3 timer/counter clock sources the timer/counter can be clocked by an internal or an external clock source. the clock source is selected by the clock select logic which is controlled by the clock select (cs02:0) bits located in the timer/counter control register (tccr0b). for details on clock sources and pres- caler, see ?timer/counter0 and timer/counter1 prescalers? on page 88 . 15.4 counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 15-2 shows a block diagram of the counter and its surroundings. figure 15-2. counter unit block diagram signal description (internal signals): table 15-1. definitions bottom the counter reaches the bottom when it becomes 0x00. max the counter reaches its maximum when it becomes 0xff (decimal 255). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr0a register. the assignment is depen- dent on the mode of operation. data b u s tcntn control logic count tovn (int.req.) clock select top tn edge detector ( from prescaler ) clk tn bottom direction clear
93 7799d?avr?11/10 atmega8u2/16u2/32u2 count increment or decrement tcnt0 by 1. direction select between increment and decrement. clear clear tcnt0 (set all bits to zero). clk t n timer/counter clock, referred to as clk t0 in the following. top signalize that tcnt0 has reached maximum value. bottom signalize that tcnt0 has reached minimum value (zero). depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t0 ). clk t0 can be generated from an external or internal clock source, selected by the clock select bits (cs0[2:0]). when no clock source is selected (cs0[2:0] = 0) the timer is stopped. however, the tcnt0 value can be accessed by the cpu, regardless of whether clk t0 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the wgm01 and wgm00 bits located in the timer/counter control register (tccr0a) and the wgm02 bit located in the timer/counter control register b (tccr0b). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs oc0a and oc0b. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 96 . the timer/counter overflow flag (tov0) is set according to the mode of operation selected by the wgm0[2:0] bits. tov0 can be used for generating a cpu interrupt. 15.5 output compare unit the 8-bit comparator continuously compares tcnt0 with the output compare registers (ocr0a and ocr0b). whenever tcnt0 equals o cr0a or ocr0b, the comparator signals a match. a match will set the output compare flag (ocf0a or ocf0b) at the next timer clock cycle. if the corresponding interrupt is enabled, the output compare flag generates an output compare interrupt. the output compare flag is automatically cleared when the interrupt is exe- cuted. alternatively, the flag can be cleared by software by writing a logical one to its i/o bit location. the waveform generator uses the match signal to generate an output according to operating mode set by the wgm0[2:0] bits and compare output mode (com0x[1:0]) bits. the max and bottom signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation ( ?modes of operation? on page 96 ). figure 15-3 shows a block diagram of the output compare unit.
94 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 15-3. output compare unit, block diagram the ocr0x registers are double buffered when using any of the pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the dou- ble buffering is disabled. the double buffering synchronizes the update of the ocr0x compare registers to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr0x register access may seem complex, but this is not case. when the double buffering is enabled, the cpu has access to the ocr0x buffer register, and if double buffering is dis- abled the cpu will access the ocr0x directly. 15.5.1 force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (foc0x) bit. forcing compare match will not set the ocf0x flag or reload/clear the timer, but the oc0x pin will be updated as if a real compare match had occurred (the com0x1:0 bits settings define whether the oc0x pin is set, cleared or toggled). 15.5.2 compare match blocking by tcnt0 write all cpu write operations to the tcnt0 register will block any compare match that occur in the next timer clock cycle, even when the timer is stopped. this feature allows ocr0x to be initial- ized to the same value as tcnt0 without triggering an interrupt when the timer/counter clock is enabled. 15.5.3 using the output compare unit since writing tcnt0 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt0 when using the output compare unit, independently of whether the timer/counter is running or not. if the value written to tcnt0 equals the ocr0x value, the compare match will be missed, resulting in incorrect waveform ocfn x (int.req.) = (8-bit comparator ) ocrnx ocnx data b u s tcntn wgmn1:0 waveform generator top focn comnx1:0 bottom
95 7799d?avr?11/10 atmega8u2/16u2/32u2 generation. similarly, do not write the tcnt0 value equal to bottom when the counter is down-counting. the setup of the oc0x should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc0x value is to use the force output com- pare (foc0x) strobe bits in normal mode. the oc0x registers keep their values even when changing between waveform generation modes. be aware that the com0x[1:0] bits are not double buffered together with the compare value. changing the com0x[1:0] bits will take effect immediately. 15.6 compare match output unit the compare output mode (com0x[1:0]) bits have two functions. the waveform generator uses the com0x[1:0] bits for defining the output compare (oc0x) state at the next compare match. also, the com0x[1:0] bits control the oc0x pin output source. figure 15-4 shows a sim- plified schematic of the logic affected by the com0x[1:0] bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control regis- ters (ddr and port) that are affected by the com0x[1:0] bits are shown. when referring to the oc0x state, the reference is for the internal oc0x register, not the oc0x pin. if a system reset occur, the oc0x register is reset to ?0?. figure 15-4. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc0x) from the waveform generator if either of the com0x1:0 bits are set. however, the oc0x pin direction (input or out- put) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the oc0x pin (ddr_oc0x) must be set as output before the oc0x value is visi- ble on the pin. the port override function is independent of the waveform generation mode. the design of the output compare pin logic allows initialization of the oc0x state before the out- put is enabled. note that some com0x1:0 bit settings are reserved for certain modes of operation. see ?register description? on page 102. port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data b u s focn clk i/o
96 7799d?avr?11/10 atmega8u2/16u2/32u2 15.6.1 compare output mode and waveform generation the waveform generator uses the com0x[1:0] bits differently in normal, ctc, and pwm modes. for all modes, setting the com0x[1:0] = 0 tells the waveform generator that no action on the oc0x register is to be performed on the next compare match. for compare output actions in the non-pwm modes refer to table 15-2 on page 102 . for fast pwm mode, refer to table 15-3 on page 102 , and for phase correct pwm refer to table 15-4 on page 103 . a change of the com0x1:0 bits state will have effect at the first compare match after the bits are written. for non-pwm modes, the action can be forced to have immediate effect by using the foc0x strobe bits. 15.7 modes of operation the mode of operation, i.e., the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm0[2:0]) and compare out- put mode (com0x[1:0]) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com0x[1:0] bits control whether the pwm output generated should be inverted or not (inverted or non-inverted pwm). for non- pwm modes the com0x[1:0] bits control whether the output should be set, cleared, or toggled at a compare match ( see ?compare match output unit? on page 95. ). for detailed timing information see ?timer/counter timing diagrams? on page 100 . 15.7.1 normal mode the simplest mode of operation is the normal mode (wgm0[2:0] = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 8-bit value (top = 0xff) and then restarts from the bot- tom (0x00). in normal operation the timer/counter overflow flag (tov0) will be set in the same timer clock cycle as the tcnt0 becomes zero. the tov0 flag in this case behaves like a ninth bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov0 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the out- put compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. 15.7.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm0[2:0] = 2), the ocr0a register is used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcnt0) matches the ocr0a. the ocr0a defines the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 15-5 . the counter value (tcnt0) increases until a compare match occurs between tcnt0 and ocr0a, and then counter (tcnt0) is cleared.
97 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 15-5. ctc mode, timing diagram an interrupt can be generated each time the counter value reaches the top value by using the ocf0a flag. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing top to a va lue close to bottom when the counter is run- ning with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr0a is lower than the current value of tcnt0, the counter will miss the compare match. the counter will then have to count to its maximum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, the oc0a output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com0a[1:0] = 1). the oc0a value will not be vi sible on the port pin unless the data direction for the pin is set to output. the waveform generated will have a maximum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero (0x00). the waveform frequency is defined by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). as for the normal mode of operation, the tov0 flag is set in the same timer clock cycle that the counter counts from max to 0x00. 15.7.3 fast pwm mode the fast pulse width modulation or fast pwm mo de (wgm0[2:0] = 3 or 7) provides a high fre- quency pwm waveform generation option. the fast pwm differs from the other pwm option by its single-slope operation. the counter counts from bottom to top then restarts from bot- tom. top is defined as 0xff when wgm0[2:0] = 3, and ocr0a when wgm0[2:0] = 7. in non- inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tcnt0 and ocr0x, and set at bottom. in inverting compare output mode, the out- put is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase correct pwm mode that use dual-slope operation. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac applications. high frequency allows physically small sized external components (coils, capacitors), and therefore reduces total system cost. in fast pwm mode, the counter is incremented until the counter value matches the top value. the counter is then cleared at the following timer clock cycle. the timing diagram for the fast tcntn ocn (toggle) ocnx interrupt flag set 1 4 period 2 3 (comnx1:0 = 1) f ocnx f clk_i/o 2 n 1 ocrnx + ?? ?? -------------------------------------------------- =
98 7799d?avr?11/10 atmega8u2/16u2/32u2 pwm mode is shown in figure 15-6 . the tcnt0 value is in the timing diagram shown as a his- togram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slopes represent com- pare matches between ocr0x and tcnt0. figure 15-6. fast pwm mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter reaches top. if the inter- rupt is enabled, the interrupt handler routine can be used for updating the compare value. in fast pwm mode, the compare unit allows ge neration of pwm waveforms on the oc0x pins. setting the com0x[1:0] bits to two will produce a non-inverted pwm and an inverted pwm out- put can be generated by setting the com0x[1:0] to three: setting the com0a[1:0] bits to one allows the oc0a pin to toggle on compare matches if the wgm02 bit is set. this option is not available for the oc0b pin (see table 15-3 on page 102 ). the actual oc0x value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by setting (or clearing) the oc0x register at the compare match between ocr0x and tcnt0, and clearing (or setting) the oc0x reg ister at the timer clock cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0a register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocr0a is set equal to bottom, the output will be a narrow spike for each max+1 timer clock cycle. setting the ocr0a equal to max will result in a constantly high or low output (depending on the polarity of the output set by the com0a1:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by set- ting oc0x to toggle its logical level on each compare match (com0x[1:0] = 1). the waveform generated will have a maximum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero. this tcntn ocrnx update and tovn interrupt flag set 1 period 2 3 ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx interrupt flag set 4 5 6 7 f ocnxpwm f clk_i/o n 256 ? ------------------ - =
99 7799d?avr?11/10 atmega8u2/16u2/32u2 feature is similar to the oc0a toggle in ctc mode, except the double buffer feature of the out- put compare unit is enabled in the fast pwm mode. 15.7.4 phase correct pwm mode the phase correct pwm mode (wgm0[2:0] = 1 or 5) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is based on a dual-slope operation. the counter counts repeatedly from bottom to top and then from top to bot- tom. top is defined as 0xff when wgm0[2:0] = 1, and ocr0a when wgm0[2:0] = 5. in non- inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tcnt0 and ocr0x while upcounting, and set on the compare match while down- counting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the sym- metric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. in phase correct pwm mode the counter is incre mented until the counter value matches top. when the counter reaches top, it changes the count direction. the tcnt0 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 15-7 . the tcnt0 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slopes represent compare matches between ocr0x and tcnt0. figure 15-7. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov0) is se t each time the counter reaches bottom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in phase correct pwm mode, the compare unit allows generation of pwm waveforms on the oc0x pins. setting the com0x1:0 bits to two will produce a non-inverted pwm. an inverted pwm output can be generated by setting the com0x[1:0] to three: setting the com0a0 bit to tovn interrupt flag set ocnx interrupt flag set 1 2 3 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx update
100 7799d?avr?11/10 atmega8u2/16u2/32u2 one allows the oc0a pin to toggle on compare matches if the wgm02 bit is set. this option is not available for the oc0b pin (see table 15-4 on page 103 ). the actual oc0x value will only be visible on the port pin if the data direction for the port pi n is set as output. the pwm wave- form is generated by clearing (or setting) the oc0x register at the compare match between ocr0x and tcnt0 when the counter increments, and setting (or clearing) the oc0x register at compare match between ocr0x and tcnt0 when the counter decrements. the pwm fre- quency for the output when using phase correct pwm can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0a register re present special cases when generating a pwm waveform output in the phase correct pwm m ode. if the ocr0a is set equal to bottom, the output will be continuously low and if set equal to max the output will be continuously high for non-inverted pwm mode. for inverted pwm the output will have the opposite logic values. at the very start of period 2 in figure 15-7 ocnx has a transition fr om high to low even though there is no compare match. the point of this transition is to guarantee symmetry around bot- tom. there are two cases that give a transition without compare match. ? ocr0a changes its value from max, like in figure 15-7 . when the ocr0a value is max the ocn pin value is the same as the result of a down-counting compare match. to ensure symmetry around bottom the ocn value at max must correspond to the result of an up- counting compare match. ? the timer starts counting from a value higher than the one in ocr0a, and for that reason misses the compare match and hence the ocn change that would have happened on the way up. 15.8 timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk t0 ) is therefore shown as a clock enable signal in the following figures. the figures include information on when interrupt flags are set. figure 15-8 contains timing data for basic timer/counter operation. the figure shows the count sequence close to the max value in all modes other than phase correct pwm mode. figure 15-8. timer/counter timing diagram, no prescaling figure 15-9 shows the same timing data, but with the prescaler enabled. f ocnxpcpwm f clk_i/o n 510 ? ------------------ - = clk tn (clk i/o /1) tovn clk i/o tcntn max - 1 max bottom bottom + 1
101 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 15-9. timer/counter timing diagram, with prescaler (f clk_i/o /8) figure 15-10 shows the setting of ocf0b in all modes and ocf0a in all modes except ctc mode and pwm mode, where ocr0a is top. figure 15-10. timer/counter timing diagram, setting of ocf0x, with prescaler (f clk_i/o /8) figure 15-11 shows the setting of ocf0a and the clearing of tcnt0 in ctc mode and fast pwm mode where ocr0a is top. figure 15-11. timer/counter timing diagram, clear timer on compare match mode, with pres- caler (f clk_i/o /8) tovn tcntn max - 1 max bottom bottom + 1 clk i/o clk tn (clk i/o /8) ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o /8) ocfnx ocrnx tcntn (ctc) top top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8)
102 7799d?avr?11/10 atmega8u2/16u2/32u2 15.9 register description 15.9.1 tccr0a ? timer/counter control register a ? bits 7:6 ? com0a[1:0]: compare match output a mode these bits control the output compare pin (oc0a) behavior. if one or both of the com0a1:0 bits are set, the oc0a output overrides the normal port functionality of the i/o pin it is connected to. however, note that the data direction register (ddr) bit corresponding to the oc0a pin must be set in order to enable the output driver. when oc0a is connected to the pin, the function of the com0a[1:0] bits depends on the wgm0[2:0] bit setting. table 15-2 shows the com0a[1:0] bit functionality when the wgm0[2:0] bits are set to a normal or ctc mode (non-pwm). table 15-3 shows the com0a[1:0] bit functionality when the wgm0[1:0] bits are set to fast pwm mode. note: 1. a special case occurs when ocr0a equals top and com0a1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 97 for more details. bit 7 6 5 4 3 2 1 0 0x24 (0x44) com0a1 com0a0 com0b1 com0b0 ? ? wgm01 wgm00 tccr0a read/write r/w r/w r/w r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0 table 15-2. compare output mode, non-pwm mode com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 0 1 toggle oc0a on compare match 1 0 clear oc0a on compare match 1 1 set oc0a on compare match table 15-3. compare output mode, fast pwm mode (1) com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 01 wgm02 = 0: normal port operation, oc0a disconnected. wgm02 = 1: toggle oc0a on compare match. 1 0 clear oc0a on compare match, set oc0a at top 1 1 set oc0a on compare match, clear oc0a at top
103 7799d?avr?11/10 atmega8u2/16u2/32u2 table 15-4 shows the com0a1:0 bit functionality when the wgm0[2:0] bits are set to phase cor- rect pwm mode. note: 1. a special case occurs when ocr0a equals top and com0a1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?phase correct pwm mode? on page 99 for more details. ? bits 5:4 ? com0b[1:0]: compare match output b mode these bits control the output compare pin (oc0b) behavior. if one or both of the com0b[1:0] bits are set, the oc0b output overrides the normal port functionality of the i/o pin it is connected to. however, note that the data direction register (ddr) bit corresponding to the oc0b pin must be set in order to enable the output driver. when oc0b is connected to the pin, the function of the com0b[1:0] bits depends on the wgm0[2:0] bit setting. table 15-2 shows the com0a[1:0] bit functionality when the wgm0[2:0] bits are set to a normal or ctc mode (non-pwm). [ table 15-3 shows the com0b[1:0] bit functionality when the wgm0[2:0] bits are set to fast pwm mode. note: 1. a special case occurs when ocr0b equals top and com0b1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 97 for more details. table 15-4. compare output mode, phase correct pwm mode (1) com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 01 wgm02 = 0: normal port operation, oc0a disconnected. wgm02 = 1: toggle oc0a on compare match. 10 clear oc0a on compare match when up-counting. set oc0a on compare match when down-counting. 11 set oc0a on compare match when up-counting. clear oc0a on compare match when down-counting. table 15-5. compare output mode, non-pwm mode com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 0 1 toggle oc0b on compare match 1 0 clear oc0b on compare match 1 1 set oc0b on compare match table 15-6. compare output mode, fast pwm mode (1) com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 0 1 reserved 1 0 clear oc0b on compare match, set oc0b at top 1 1 set oc0b on compare match, clear oc0b at top
104 7799d?avr?11/10 atmega8u2/16u2/32u2 table 15-4 shows the com0b[1:0] bit functionality when the wgm0[2:0] bits are set to phase correct pwm mode. note: 1. a special case occurs when ocr0b equals top and com0b1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?phase correct pwm mode? on page 99 for more details. ? bits 3:2 ? res: reserved bits these bits are reserved and will always read as zero. ? bits 1:0 ? wgm0[1:0]: waveform generation mode combined with the wgm02 bit found in the tccr0b register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and what type of wave- form generation to be used, see table 15-8 . modes of operation supported by the timer/counter unit are: normal mode (counter), clear timer on compare match (ctc) mode, and two types of pulse width modulation (pwm) modes (see ?modes of operation? on page 96 ). notes: 1. max = 0xff 2. bottom = 0x00 table 15-7. compare output mode, phase correct pwm mode (1) com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 0 1 reserved 10 clear oc0b on compare match when up-counting. set oc0b on compare match when down-counting. 11 set oc0b on compare match when up-counting. clear oc0b on compare match when down-counting. table 15-8. waveform generation mode bit description mode wgm2 wgm1 wgm0 timer/counter mode of operation top update of ocrx at tov flag set on (1)(2) 0 0 0 0 normal 0xff immediate max 1001 pwm, phase correct 0xff top bottom 2 0 1 0 ctc ocra immediate max 3 0 1 1 fast pwm 0xff top max 4 1 0 0 reserved ? ? ? 5101 pwm, phase correct ocra top bottom 6 1 1 0 reserved ? ? ? 7 1 1 1 fast pwm ocra top top
105 7799d?avr?11/10 atmega8u2/16u2/32u2 15.9.2 tccr0b ? timer/counter control register b ? bit 7 ? foc0a: force output compare a the foc0a bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr0b is written when operating in pwm mode. when writing a logical one to the foc0a bit, an immediate compare match is forced on the waveform generation unit. the oc0a output is changed according to its com0a1:0 bits setting. note that the foc0a bit is implemented as a strobe. therefore it is the value present in the co m0a1:0 bits that determines the effect of the forced compare. a foc0a strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0a as top. the foc0a bit is always read as zero. ? bit 6 ? foc0b: force output compare b the foc0b bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr0b is written when operating in pwm mode. when writing a logical one to the foc0b bit, an immediate compare match is forced on the waveform generation unit. the oc0b output is changed according to its com0b[1:0] bits setting. note that the foc0b bit is implemented as a strobe. therefore it is the value present in the com0b[1:0] bits that determines the effect of the forced compare. a foc0b strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0b as top. the foc0b bit is always read as zero. ? bits 5:4 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bit 3 ? wgm02: waveform generation mode see the description in the ?tccr0a ? timer/counter control register a? on page 102 . ? bits 2:0 ? cs0[2:0]: clock select the three clock select bits select the clock source to be used by the timer/counter. bit 7 6 5 4 3 2 1 0 0x25 (0x45) foc0a foc0b ? ? wgm02 cs02 cs01 cs00 tccr0b read/write w w r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 15-9. clock select bit description cs02 cs01 cs00 description 0 0 0 no clock source (timer/counter stopped) 0 0 1 clk i/o /(no prescaling) 0 1 0 clk i/o /8 (from prescaler) 0 1 1 clk i/o /64 (from prescaler)
106 7799d?avr?11/10 atmega8u2/16u2/32u2 if external pin modes are used for the timer/counter0, transitions on the t0 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. 15.9.3 tcnt0 ? timer/counter register the timer/counter register gives direct access, both for read and write operations, to the timer/counter unit 8-bit counter. writing to the tcnt0 register blocks (removes) the compare match on the following timer clock. modifying the counter (tcnt0) while the counter is running, introduces a risk of missing a compare match between tcnt0 and the ocr0x registers. 15.9.4 ocr0a ? output compare register a the output compare register a contains an 8-bit value that is continuously compared with the counter value (tcnt0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0a pin. 15.9.5 ocr0b ? output compare register b the output compare register b contains an 8-bit value that is continuously compared with the counter value (tcnt0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0b pin. 15.9.6 timsk0 ? timer/counter interrupt mask register ? bits 7:3 ? res: reserved bits these bits are reserved bits and will always read as zero. 1 0 0 clk i/o /256 (from prescaler) 1 0 1 clk i/o /1024 (from prescaler) 1 1 0 external clock source on t0 pin. clock on falling edge. 1 1 1 external clock source on t0 pin. clock on rising edge. table 15-9. clock select bit description (continued) cs02 cs01 cs00 description bit 76543210 0x26 (0x46) tcnt0[7:0] tcnt0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x27 (0x47) ocr0a[7:0] ocr0a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x28 (0x48) ocr0b[7:0] ocr0b read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543 2 10 (0x6e) ? ? ? ? ? ocie0b ocie0a toie0 timsk0 read/write r r r r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0
107 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 2 ? ocie0b: timer/counter output compare match b interrupt enable when the ocie0b bit is written to one, and the i-bit in the status register is set, the timer/counter compare match b interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter occurs, i.e., when the ocf0b bit is set in the timer/counter interrupt flag register ? tifr0. ? bit 1 ? ocie0a: timer/counter0 output compare match a interrupt enable when the ocie0a bit is written to one, and the i-bit in the status register is set, the timer/counter0 compare match a interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter0 occurs, i.e., when the ocf0a bit is set in the timer/counter 0 interrupt flag register ? tifr0. ? bit 0 ? toie0: timer/counter0 overflow interrupt enable when the toie0 bit is written to one, and the i-bit in the status register is set, the timer/counter0 overflow interrupt is enabled. the corresponding interrupt is executed if an overflow in timer/counter0 occu rs, i.e., when the tov0 bit is se t in the timer/counter 0 inter- rupt flag register ? tifr0. 15.9.7 tifr0 ? timer/counter 0 interrupt flag register ? bits 7:3 ? res: reserved bits these bits are reserved and will always read as zero. ? bit 2 ? ocf0b: timer/counter 0 output compare b match flag the ocf0b bit is set when a compare match occurs between the timer/counter and the data in ocr0b ? output compare register0 b. ocf0b is cleared by hardware when executing the cor- responding interrupt handling vector. alternatively, ocf0b is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie0b (timer/counter compare b match interrupt enable), and ocf0b are set, the timer/counter compare match interrupt is executed. ? bit 1 ? ocf0a: timer/counter 0 output compare a match flag the ocf0a bit is set when a compare match occurs between the timer/counter0 and the data in ocr0a ? output compare register0. ocf0a is cleared by hardware when executing the cor- responding interrupt handling vector. alternatively, ocf0a is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie0a (timer/counter0 compare match interrupt enable), and ocf0a are set, the timer/counter0 compare match interrupt is executed. ? bit 0 ? tov0: timer/counter0 overflow flag the bit tov0 is set when an overflow occurs in timer/counter0. tov0 is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, tov0 is cleared by writing a logic one to the flag. when the sreg i-bit, toie0 (timer/counter0 overflow interrupt enable), and tov0 are set, the timer/counter0 overflow interrupt is executed. the setting of this flag is dependent of the wgm0[2 :0] bit setting. refer to table 15-8 , ?wave- form generation mode bit description? on page 104 . bit 76543210 0x15 (0x35) ? ? ? ? ? ocf0b ocf0a tov0 tifr0 read/write r r r r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0
108 7799d?avr?11/10 atmega8u2/16u2/32u2 16. 16-bit timer/counter 1 with pwm 16.1 features ? true 16-bit design (i.e., allows 16-bit pwm) ? three independent output compare units ? double buffered output compare registers ? one input capture unit ? input capture noise canceler ? clear timer on compare match (auto reload) ? glitch-free, phase correct pulse width modulator (pwm) ? variable pwm period ? frequency generator ? external event counter ? five independent interrupt sources (tov1, ocf1a, ocf1b, ocf1c, icf1) 16.2 overview the 16-bit timer/counter 1 unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. most register and bit references in this sec- tion are written in general form. a lower case ?n? replaces the timer/counter number (for this product, only n=1 is available), and a lower case ?x? replaces the output compare unit channel. however, when using the register or bit defines in a program, the precise form must be used, i.e., tcnt1 for accessing timer/counter1 counter value and so on. a simplified block diagram of the 16-bit timer/counter is shown in figure 16-1 . for the actual placement of i/o pins, see ?pinout? on page 2 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the device-speci fic i/o register and bit locations are listed in the ?16-bit timer/counter 1 with pwm? on page 108 . the power reduction timer/counter1 bit, prtim1, in ?prr0 ? power reduction register 0? on page 46 must be written to zero to enable timer/counter1 module.
109 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 16-1. 16-bit timer/counter block diagram (1) note: 1. refer to figure 1-1 on page 2 , table 12-3 on page 74 , and table 12-6 on page 77 for timer/counter1 pin placement and description. 16.2.1 registers the timer/counter (tcntn), output compare registers (ocrna/b/c), and input capture reg- ister (icrn) are all 16-bit registers. special procedures must be followed when accessing the 16- bit registers. these procedures are described in the section ?accessing 16-bit registers? on page 110 . the timer/counter control registers (tccrna/b/c) are 8-bit registers and have no cpu access restrictions. interrupt requests (shorten as int.req.) signals are all visible in the timer interrupt flag register (tifrn). all interrupts are individually masked with the timer inter- rupt mask register (timskn). tifrn and timskn are not shown in the figure since these registers are shared by other timer units. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the tn pin. the clock select logic block controls which clock source and edge the timer/counter uses to increment (or decrement) its value. the timer/counter is inactive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t n ). the double buffered output compare registers (ocrna/b/c) are compared with the timer/counter value at all time. the result of the compare can be used by the waveform gener- ator to generate a pwm or variable frequency output on the output compare pin (ocna/b/c). icfn (int.req.) tovn (int.req.) clock select timer/counter databus icrn = = = tcntn waveform generation waveform generation waveform generation ocna ocnb ocnc noise canceler icpn = fixed top values edge detector control logic = 0 top bottom count clear direction ocfna (int.req.) ocfnb (int.req.) ocfnc (int.req.) tccrna tccrnb tccrnc ( from analog comparator ouput ) tn edge detector ( from prescaler ) tclk ocrnc ocrnb ocrna
110 7799d?avr?11/10 atmega8u2/16u2/32u2 see ?output compare units? on page 117. . the compare match event will also set the compare match flag (ocfna/b/c) which can be used to generate an output compare interrupt request. the input capture register can capture the timer/counter value at a given external (edge trig- gered) event on either the input capture pin (icpn) or on the analog comparator pins ( see ?analog comparator? on page 223. ) the input capture unit includes a digital filtering unit (noise canceler) for reducing the chance of capturing noise spikes. the top value, or maximum timer/counter value, can in some modes of operation be defined by either the ocrna register, the icrn register, or by a set of fixed values. when using ocrna as top value in a pwm mode, the ocrna register can not be used for generating a pwm output. however, the top value will in this case be double buffered allowing the top value to be changed in run time. if a fixed top value is required, the icrn register can be used as an alternative, freeing the ocrna to be used as pwm output. 16.2.2 definitions the following definitions are used extensively throughout the document: 16.3 accessing 16-bit registers the tcntn, ocrna/b/c, and icrn are 16-bit registers that can be accessed by the avr cpu via the 8-bit data bus. the 16-bit register must be byte accessed using two read or write opera- tions. each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16- bit access. the same temporary register is shared between all 16-bit registers within each 16- bit timer. accessing the low byte triggers the 16-bit read or write operation. when the low byte of a 16-bit register is written by the cpu, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clock cycle. when the low byte of a 16-bit register is read by the cpu, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. not all 16-bit accesses uses the temporary register for the high byte. reading the ocrna/b/c 16-bit registers does not involve using the temporary register. to do a 16-bit write, the high byte must be written before the low byte. for a 16-bit read, the low byte must be read before the high byte. the following code examples show how to access the 16-bit timer registers assuming that no interrupts updates the temporary register. the same principle can be used directly for accessing the ocrna/b/c and icrn registers. note that when using ?c?, the compiler handles the 16-bit access. bottom the counter reaches the bottom when it becomes 0x0000. max the counter reaches its max imum when it becomes 0xffff (decimal 65535). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be one of the fixed values: 0x00ff, 0x01ff, or 0x03ff, or to the value stored in the ocrna or icrn register. the assignment is dependent of the mode of operation.
111 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. see ?code examples? on page 6. the assembly code example returns the tcntn value in the r17:r16 register pair. it is important to notice that accessing 16-bit registers are atomic operations. if an interrupt occurs between the two instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or any other of the 16-bit timer regis- ters, then the result of the access outside the in terrupt will be corrupted. therefore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access. the following code examples show how to do an atomic read of the tcntn register contents. reading any of the ocrna/b/c or icrn registers can be done by using the same principle. assembly code examples (1) ... ; set tcntn to 0x01ff ldi r17,0x01 ldi r16,0xff out tcntnh,r17 out tcntnl,r16 ; read tcntn into r17:r16 in r16,tcntnl in r17,tcntnh ... c code examples (1) unsigned int i; ... /* set tcntn to 0x01ff */ tcntn = 0x1ff; /* read tcntn into i */ i = tcntn; ...
112 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. see ?code examples? on page 6. the assembly code example returns the tcntn value in the r17:r16 register pair. assembly code example (1) tim16_readtcntn: ; save global interrupt flag in r18,sreg ; disable interrupts cli ; read tcntn into r17:r16 in r16,tcntnl in r17,tcntnh ; restore global interrupt flag out sreg,r18 ret c code example (1) unsigned int tim16_readtcntn( void ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ __disable_interrupt(); /* read tcntn into i */ i = tcntn; /* restore global interrupt flag */ sreg = sreg; return i; }
113 7799d?avr?11/10 atmega8u2/16u2/32u2 the following code examples show how to do an atomic write of the tcntn register contents. writing any of the ocrna/b/c or icrn registers can be done by using the same principle. note: 1. see ?code examples? on page 6. the assembly code example requires that the r17:r16 register pair contains the value to be writ- ten to tcntn. 16.3.1 reusing the temporary high byte register if writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. however, note that the same rule of atomic operation described previously also applies in this case. 16.4 timer/counter clock sources the timer/counter can be clocked by an internal or an external clock source. the clock source is selected by the clock select logic which is controlled by the clock select (csn2:0) bits located in the timer/counter control register b (tccrnb). for details on clock sources and prescaler, see ?timer/counter0 and timer/counter1 prescalers? on page 88 . assembly code example (1) tim16_writetcntn: ; save global interrupt flag in r18,sreg ; disable interrupts cli ; set tcntn to r17:r16 out tcntnh,r17 out tcntnl,r16 ; restore global interrupt flag out sreg,r18 ret c code example (1) void tim16_writetcntn( unsigned int i ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ __disable_interrupt(); /* set tcntn to i */ tcntn = i; /* restore global interrupt flag */ sreg = sreg; }
114 7799d?avr?11/10 atmega8u2/16u2/32u2 16.5 counter unit the main part of the 16-bit timer/counter is the programmable 16-bit bi-directional counter unit. figure 16-2 shows a block diagram of the counter and its surroundings. figure 16-2. counter unit block diagram signal description (internal signals): count increment or decrement tcntn by 1. direction select between increment and decrement. clear clear tcntn (set all bits to zero). clk t n timer/counter clock. top signalize that tcntn has reached maximum value. bottom signalize that tcntn has reached minimum value (zero). the 16-bit counter is mapped into two 8-bit i/o memory locations: counter high (tcntnh) con- taining the upper eight bits of the counter, and counter low (tcntnl) containing the lower eight bits. the tcntnh register can only be indirectly accessed by the cpu. when the cpu does an access to the tcntnh i/o location, the cpu accesses the high byte temporary register (temp). the temporary register is updated with the tcntnh value when the tcntnl is read, and tcntnh is updated with the temporary register v alue when tcntnl is written. this allows the cpu to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data bus. it is important to notice that there are specia l cases of writing to th e tcntn register when the counter is counting that will give unpredictable results. the special cases are described in the sections where they are of importance. depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t n ). the clk t n can be generated from an external or internal clock source, selected by the clock select bits (csn2:0). when no clock source is selected (csn2:0 = 0) the timer is stopped. however, the tcntn value can be accessed by the cpu, independent of whether clk t n is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the waveform generation mode bits (wgmn3:0) located in the timer/counter control registers a and b (tccrna and tccrnb). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs ocnx. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 120 . temp (8-bit) data bus (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) control logic count clear direction tovn (int.req.) clock select top bottom tn edge detector ( from prescaler ) clk tn
115 7799d?avr?11/10 atmega8u2/16u2/32u2 the timer/counter overflow flag (tovn) is set according to the mode of operation selected by the wgmn3:0 bits. tovn can be used for generating a cpu interrupt. 16.6 input capture unit the timer/counter incorporates an input capture unit that can capture external events and give them a time-stamp indicating time of occurrence. the external signal indicating an event, or mul- tiple events, can be applied via the icpn pin or alternatively, for the timer/counter1 only, via the analog comparator unit. the time-stamps can then be used to calculate frequency, duty-cycle, and other features of the signal applied. alternatively the time-stamps can be used for creating a log of the events. the input capture unit is illustrated by the block diagram shown in figure 16-3 . the elements of the block diagram that are not directly a part of the input capture unit are gray shaded. the small ?n? in register and bit names indicates the timer/counter number. figure 16-3. input capture unit block diagram note: the analog comparator output (aco) can only trigger the timer/counter1 icp ? not timer/counter3, 4 or 5. when a change of the logic level (an event) occurs on the input capture pin (icpn), alternatively on the analog comparator output (aco), and this change confirms to the setting of the edge detector, a capture will be triggered. when a capture is triggered, the 16-bit value of the counter (tcntn) is written to the input capture register (icrn). the input capture flag (icfn) is set at the same system clock as the tcntn value is c opied into icrn register. if enabled (ticien = 1), the input capture flag generates an input capture interrupt. the icfn flag is automatically cleared when the interrupt is executed. alternatively the icfn flag can be cleared by software by writing a logical one to its i/o bit location. icfn (int.req.) analog comparator write icrn (16-bit register) icrnh (8-bit) noise canceler icpn edge detector temp (8-bit) data b u s (8-bit) icrnl (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) acic* icnc ices aco*
116 7799d?avr?11/10 atmega8u2/16u2/32u2 reading the 16-bit value in the input capture register (icrn) is done by first reading the low byte (icrnl) and then the high byte (icrnh). when the low byte is read the high byte is copied into the high byte temporary register (temp). when the cpu reads the icrnh i/o location it will access the temp register. the icrn register can only be written when using a waveform generation mode that utilizes the icrn register for defining the count er?s top value. in these cases the waveform genera- tion mode (wgmn3:0) bits must be set before the top value can be written to the icrn register. when writing the icrn register the high byte must be written to the icrnh i/o location before the low byte is written to icrnl. for more information on how to access the 16-bit registers refer to ?accessing 16-bit registers? on page 110 . 16.6.1 input capture trigger source the main trigger source for the input capture unit is the input capture pin (icpn). timer/counter1 can alternatively use the analog comparator output as trigger source for the input capture unit. the analog comparator is selected as trigger source by setting the analog comparator input capture (acic) bit in the analog comparator control and status register (acsr). be aware that changing trigger source can trigger a capture. the input capture flag must therefore be cleared after the change. both the input capture pin (icpn) and the analog comparator output (aco) inputs are sampled using the same technique as for the tn pin ( figure 14-1 on page 88 ). the edge detector is also identical. however, when the noise canceler is enabled, additional logic is inserted before the edge detector, which increases the delay by four system clock cycles. note that the input of the noise canceler and edge detector is always enabled unless the timer/counter is set in a wave- form generation mode that uses icrn to define top. an input capture can be triggered by software by controlling the port of the icpn pin. 16.6.2 noise canceler the noise canceler improves noise immunity by using a simple digital filtering scheme. the noise canceler input is monitored over four samples, and all four must be equal for changing the output that in turn is used by the edge detector. the noise canceler is enabled by setting the input capture noise canceler (icncn) bit in timer/counter control register b (tccrnb). when enabled the noise canceler introduces addi- tional four system clock cycles of delay from a change applied to the input, to the update of the icrn register. the noise canceler uses the system clock and is therefore not affected by the prescaler. 16.6.3 using the input capture unit the main challenge when using the input capture unit is to assign enough processor capacity for handling the incoming events. the time between two events is critical. if the processor has not read the captured value in the icrn register before the next event occurs, the icrn will be overwritten with a new value. in this case the result of the capture will be incorrect. when using the input capture interrupt, the icrn register should be read as early in the inter- rupt handler routine as possible. even though the input capture interrupt has relatively high priority, the maximum interrupt response time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests.
117 7799d?avr?11/10 atmega8u2/16u2/32u2 using the input capture unit in any mode of operation when the top value (resolution) is actively changed during operation, is not recommended. measurement of an external signal?s duty cycle requires that the trigger edge is changed after each capture. changing the edge sensing must be done as early as possible after the icrn register has been read. after a change of the edge, the input capture flag (icfn) must be cleared by software (writing a logical one to the i/o bit location). for measuring frequency only, the clearing of the icfn flag is not required (if an interrupt handler is used). 16.7 output compare units the 16-bit comparator continuously compares tcntn with the output compare register (ocrnx). if tcnt equals ocrnx the comparat or signals a match. a match will set the output compare flag (ocfnx) at the next timer clock cycle. if enabled (ocienx = 1), the output com- pare flag generates an output compare interrupt. the ocfnx flag is automatically cleared when the interrupt is executed. alternatively the ocfnx flag can be cleared by software by writ- ing a logical one to its i/o bit location. the waveform generator uses the match signal to generate an output according to operating mode set by the waveform generation mode (wgmn3:0) bits and compare output mode (comnx1:0) bits. the top and bottom signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation ( see ?modes of operation? on page 120. ) a special feature of output compare unit a allows it to define the timer/counter top value (i.e., counter resolution). in addition to the counter resolution, the top value defines the period time for waveforms generated by the waveform generator. figure 16-4 shows a block diagram of the output compare unit. the small ?n? in the register and bit names indicates the device number (n = n for timer/counter n), and the ?x? indicates output compare unit (a/b/c). the elements of the block diagram that are not directly a part of the out- put compare unit are gray shaded. figure 16-4. output compare unit, block diagram ocfnx (int.req.) = (16-bit comparator ) ocrnx buffer (16-bit register) ocrnxh buf. (8-bit) ocnx temp (8-bit) data b u s (8-bit) ocrnxl buf. (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) comnx1:0 wgmn3:0 ocrnx (16-bit register) ocrnxh (8-bit) ocrnxl (8-bit) waveform generator top bottom
118 7799d?avr?11/10 atmega8u2/16u2/32u2 the ocrnx register is double buffered when using any of the twelve pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the double buffering is disabled. the double buffering synchronizes the update of the ocrnx com- pare register to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-s ymmetrical pwm pulses, thereby making the out- put glitch-free. the ocrnx register access may seem complex, but this is not case. when the double buffering is enabled, the cpu has access to the ocrnx buffer register, and if double buffering is dis- abled the cpu will access the ocrnx directly. the content of the ocr1x (buffer or compare) register is only changed by a write operation (the timer/counter does not update this register automatically as the tcnt1 and icr1 register). therefore ocr1x is not read via the high byte temporary register (temp). however, it is a good practice to read the low byte first as when accessing other 16-bit registers. writing the ocrnx registers must be done via the temp reg- ister since the compare of all 16 bits is done continuously. the high byte (ocrnxh) has to be written first. when the high byte i/o location is written by the cpu, the temp register will be updated by the value written. then when the low byte (ocrnxl) is written to the lower eight bits, the high byte will be copied into the upper 8-bits of either the ocrnx buffer or ocrnx compare register in the same system clock cycle. for more information of how to access the 16-bit registers refer to ?accessing 16-bit registers? on page 110 . 16.7.1 force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (focnx) bit. forcing compare match will not set the ocfnx flag or reload/clear the timer, but the ocnx pin will be updated as if a real compare match had occurred (the comn1:0 bits settings def ine whether the ocnx pin is set, cleared or toggled). 16.7.2 compare match blocking by tcntn write all cpu writes to the tcntn register will block any compare match that occurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocrnx to be initialized to the same value as tcntn without triggering an interrupt when the timer/counter clock is enabled. 16.7.3 using the output compare unit since writing tcntn in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing tcntn when using any of the output compare channels, independent of whether the timer/counter is running or not. if the value written to tcntn equals the ocrnx value, the compare match will be missed, resulting in incorrect wave- form generation. do not write the tcntn equal to top in pwm modes with variable top values. the compare match for the top will be ignored and the counter will continue to 0xffff. similarly, do not write the tcntn value equal to bottom when the counter is downcounting. the setup of the ocnx should be performed before setting the data direction register for the port pin to output. the easiest way of setting the ocnx value is to use the force output com- pare (focnx) strobe bits in normal mode. the ocnx register keeps its value even when changing between waveform generation modes. be aware that the comnx1:0 bits are not double buffered together with the compare value. changing the comnx1:0 bits will take effect immediately.
119 7799d?avr?11/10 atmega8u2/16u2/32u2 16.8 compare match output unit the compare output mode (comnx1:0) bits have two functions. the waveform generator uses the comnx1:0 bits for defining the output compare (ocnx) state at the next compare match. secondly the comnx1:0 bits control the ocnx pin output source. figure 16-5 shows a simplified schematic of the logic affected by the comnx1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the comnx1:0 bits are shown. when referring to the ocnx state, the reference is for the internal ocnx register, not the ocnx pin. if a system reset occur, the ocnx register is reset to ?0?. figure 16-5. compare match output unit, schematic the general i/o port function is overridden by the output compare (ocnx) from the waveform generator if either of the comnx1:0 bits are set. however, the ocnx pin direction (input or out- put) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the ocnx pin (ddr_ocnx) must be set as output before the ocnx value is visi- ble on the pin. the port override function is generally independent of the waveform generation mode, but there are some exceptions. refer to table 16-1 , table 16-2 and table 16-3 for details. the design of the output compare pin logic allows initialization of the ocnx state before the out- put is enabled. note that some comnx1:0 bit settings are reserved for certain modes of operation. see ?16-bit timer/counter 1 with pwm? on page 108. the comnx1:0 bits have no effect on the input capture unit. 16.8.1 compare output mode and waveform generation the waveform generator uses the comnx1:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the comnx1:0 = 0 tells the waveform generator that no action on the ocnx register is to be performed on the next compare match. for compare output actions in the port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data b u s focnx clk i/o
120 7799d?avr?11/10 atmega8u2/16u2/32u2 non-pwm modes refer to table 16-1 on page 130 . for fast pwm mode refer to table 16-2 on page 130 , and for phase correct and phase and frequency correct pwm refer to table 16-3 on page 131 . a change of the comnx1:0 bits state will have effect at the first compare match after the bits are written. for non-pwm modes, the action can be forced to have immediate effect by using the focnx strobe bits. 16.9 modes of operation the mode of operation, i.e., the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgmn3:0) and compare output mode (comnx1:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the comnx1:0 bits control whether the pwm out- put generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the comnx1:0 bits control whether the output should be set, cleared or toggle at a compare match ( see ?compare match output unit? on page 119. ) for detailed timing information refer to ?timer/counter timing diagrams? on page 127 . 16.9.1 normal mode the simplest mode of operation is the normal mode (wgmn3:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 16-bit value (max = 0xffff) and then restarts from the bottom (0x0000). in normal operation the timer/counter overflow flag (tovn) will be set in the same timer clock cycle as the tcntn become s zero. the tovn flag in this case behaves like a 17th bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tovn flag, the timer resolution can be increased by soft- ware. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the input capture unit is easy to use in normal mode. however, observe that the maximum interval between the external events must not exceed the resolution of the counter. if the interval between events are too long, the timer overflow interrupt or the prescaler must be used to extend the resolution for the capture unit. the output compare units can be used to generate interrupts at some given time. using the output compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. 16.9.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgmn[3:0] = 4 or 12), the ocrna or icrn register are used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcntn) matches either the ocrna (wgmn[3:0] = 4) or the icrn (wgmn[3:0] = 12). the ocrna or icrn define the top value for the counter, hence also its res- olution. this mode allows greater control of the compare match output frequency. it also simplifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 16-6 . the counter value (tcntn) increases until a compare match occurs with either ocrna or icrn, and then counter (tcntn) is cleared.
121 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 16-6. ctc mode, timing diagram an interrupt can be generated at each time the counter value reaches the top value by either using the ocfna or icfn flag according to the register used to define the top value. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. how- ever, changing the top to a value close to bottom when the counter is running with none or a low prescaler value must be done with care since the ctc mode does not have the double buff- ering feature. if the new value written to ocrna or icrn is lower than the current value of tcntn, the counter will miss the compare match. the counter will then have to count to its max- imum value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. in many cases this feature is not desirable. an alternative will then be to use the fast pwm mode using ocrna for defining top (wgmn3:0 = 15) since the ocrna then will be double buffered. for generating a waveform output in ctc mode, the ocna output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (comna1:0 = 1). the ocna value will not be visible on the port pin unless the data direction for the pin is set to output (ddr_ocna = 1). the waveform generated will have a maximum fre- quency of f oc n a = f clk_i/o /2 when ocrna is set to zero (0x0000). the waveform frequency is defined by the following equation: the n variable represents the prescaler factor (1, 8, 64, 256, or 1024). as for the normal mode of operation, the tovn flag is set in the same timer clock cycle that the counter counts from max to 0x0000. 16.9.3 fast pwm mode the fast pulse width modulation or fast pwm mode (wgmn[3:0] = 5, 6, 7, 14, or 15) provides a high frequency pwm waveform generation option. the fast pwm differs from the other pwm options by its single-slope operation. the counter counts from bottom to top then restarts from bottom. in non-inverting compare output mode, the output compare (ocnx) is set on the compare match between tcntn and ocrnx, and cleared at top. in inverting compare output mode output is cleared on compare match and set at top. due to the single-slope oper- ation, the operating frequency of the fast pwm mode can be twice as high as the phase correct and phase and frequency correct pwm modes that use dual-slope operation. this high fre- quency makes the fast pwm mode well suited for power regulation, rectification, and dac applications. high frequency allows physically small sized external components (coils, capaci- tors), hence reduces total system cost. tcntn ocna (toggle) ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 4 period 2 3 (comna1:0 = 1) f ocna f clk_i/o 2 n 1 ocrna + ? ? ?? -------------------------------------------------- - =
122 7799d?avr?11/10 atmega8u2/16u2/32u2 the pwm resolution for fast pwm can be fixed to 8-, 9-, or 10-bit, or defined by either icrn or ocrna. the minimum resolution allowed is 2-bit (icrn or ocrna set to 0x0003), and the max- imum resolution is 16-bit (icrn or ocrna set to max). the pwm resolution in bits can be calculated by using the following equation: in fast pwm mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgmn[3:0] = 5, 6, or 7), the value in icrn (wgmn[3:0] = 14), or the value in ocrna (wgmn[3:0] = 15). the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 16-7 . the figure shows fast pwm mode when ocrna or icrn is used to define top. the tcntn value is in the timing diagram shown as a histogram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcntn slopes represent compare matches between ocrnx and tcntn. the ocnx interrupt flag will be set when a compare match occurs. figure 16-7. fast pwm mode, timing diagram the timer/counter overflow flag (tovn) is set each time the counter reaches top. in addition the ocna or icfn flag is set at the same timer clock cycle as tovn is set when either ocrna or icrn is used for defining the top value. if one of the interrupts are enabled, the interrupt han- dler routine can be used for updating the top and compare values. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcntn and the ocrnx. note that when using fixed top values the unused bits are masked to zero when any of the ocrnx registers are written. the procedure for updating icrn differs from updating ocrna when used for defining the top value. the icrn register is not double buffered. this means that if icrn is changed to a low value when the counter is running with none or a low prescaler value, there is a risk that the new icrn value written is lower than the current value of tcntn. the result will then be that the counter will miss the compare match at the top value. the counter will then have to count to the max value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. the ocrna register however, is double buffered . this feature allows the ocrna i/o location r fpwm top 1 + ?? log 2 ?? log ---------------------------------- - = tcntn ocrnx / top update and tovn interrupt flag set and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 7 period 2 3 4 5 6 8 ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
123 7799d?avr?11/10 atmega8u2/16u2/32u2 to be written anytime. when the ocrna i/o locat ion is written the value written will be put into the ocrna buffer register. the ocrna compare register will then be updated with the value in the buffer register at the next timer clock cycle the tcntn matches top. the update is done at the same timer clock cycle as the tcntn is cleared and the tovn flag is set. using the icrn register for defining top works well when using fixed top values. by using icrn, the ocrna register is free to be used for generating a pwm output on ocna. however, if the base pwm frequency is actively changed (by changing the top value), using the ocrna as top is clearly a better choice due to its double buffer feature. in fast pwm mode, the compare units allow ge neration of pwm waveforms on the ocnx pins. setting the comnx1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the comnx1:0 to three (see table on page 130 ). the actual ocnx value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_ocnx). the pwm waveform is generated by setting (or clearing) the ocnx register at the compare match between ocrnx and tcntn, and clearing (or setting) the ocnx register at the timer clock cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocrnx register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocrnx is set equal to bottom (0x0000) the out- put will be a narrow spike for each top+1 timer clock cycle. setting the ocrnx equal to top will result in a constant high or low output (depending on the polarity of the output set by the comnx1:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by set- ting ocna to toggle its logical level on each compare match (comna1:0 = 1). this applies only if ocr1a is used to define the top value (wgm13:0 = 15). the waveform generated will have a maximum frequency of f oc n a = f clk_i/o /2 when ocrna is set to zero (0x0000). this feature is similar to the ocna toggle in ctc mode, except the double buffer feature of the output com- pare unit is enabled in the fast pwm mode. 16.9.4 phase correct pwm mode the phase correct pulse width modulation or phase correct pwm mode (wgmn[3:0] = 1, 2, 3, 10, or 11) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is, like the phase and frequency correct pwm mode, based on a dual- slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare output mode, the output compare (ocnx) is cleared on the compare match between tcntn and ocrnx while upcounting, and set on the compare match while downcounting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmetric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. the pwm resolution for the phase correct pwm mode can be fixed to 8-, 9-, or 10-bit, or defined by either icrn or ocrna. the minimum resolution allowed is 2-bit (icrn or ocrna set to f ocnxpwm f clk_i/o n 1 top + ? ? ? ---------------------------------- - =
124 7799d?avr?11/10 atmega8u2/16u2/32u2 0x0003), and the maximum resolution is 16-bit (icrn or ocrna set to max). the pwm resolu- tion in bits can be calculated by using the following equation: in phase correct pwm mode the counter is incre mented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgmn[3:0] = 1, 2, or 3), the value in icrn (wgmn[3:0] = 10), or the value in ocrna (wgmn3:0 = 11). the counter has then reached the top and changes the count direction. the tcntn value will be equal to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 16-8 . the figure shows phase correct pwm mode when ocrna or icrn is used to define top. the tcntn value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcntn slopes represent compare matches between ocrnx and tcntn. the ocnx inter- rupt flag will be set when a compare match occurs. figure 16-8. phase correct pwm mode, timing diagram the timer/counter overflow flag (tovn) is set each time the counter reaches bottom. when either ocrna or icrn is used for defining the top value, the ocna or icfn flag is set accord- ingly at the same timer clock cycle as the ocrnx registers are updated with the double buffer value (at top). the interrupt flags can be used to generate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcntn and the ocrnx. note that when using fixed top values, the unused bits are masked to zero when any of the ocrnx registers are written. as the third period shown in figure 16-8 illustrates, changing the top actively while the timer/counter is running in the phase correct mode can result in an unsymmetrical output. the reason for this can be found in the time of update of the ocrnx reg- r pcpwm top 1 + ?? log 2 ?? log ---------------------------------- - = ocrnx/top update and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 2 3 4 tovn interrupt flag set (interrupt on bottom) tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
125 7799d?avr?11/10 atmega8u2/16u2/32u2 ister. since the ocrnx update occurs at top, the pwm period starts and ends at top. this implies that the length of the falling slope is determined by the previous top value, while the length of the rising slope is determined by the new top value. when these two values differ the two slopes of the period will differ in length. the difference in length gives the unsymmetrical result on the output. it is recommended to use the phase and frequency correct mode instead of the phase correct mode when changing the top value while the timer/counter is running. when using a static top value there are practically no differences between the two modes of operation. in phase correct pwm mode, the compare units allow generation of pwm waveforms on the ocnx pins. setting the comnx[1:0] bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the comnx[1:0] to three (see table 16-3 on page 131 ). the actual ocnx value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_ocnx). the pwm waveform is generated by setting (or clearing) the ocnx register at the compare match between ocrnx and tcntn when the counter incre- ments, and clearing (or setting) the ocnx register at compare match between ocrnx and tcntn when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the oc rnx register represent specia l cases when ge nerating a pwm waveform output in the phase correct pwm mode. if the ocrnx is set equal to bottom the output will be continuously low and if set equal to top the output will be continuously high for non-inverted pwm mode. for inverted pwm the output will have the opposite logic values. if ocr1a is used to define the top value (wgm13:0 = 11) and com1a[1:0] = 1, the oc1a out- put will toggle with a 50% duty cycle. 16.9.5 phase and frequency correct pwm mode the phase and frequency correct pulse width modulation, or phase and frequency correct pwm mode (wgmn[3:0] = 8 or 9) provides a high resolution phase and frequency correct pwm wave- form generation option. the phase and frequency correct pwm mode is, like the phase correct pwm mode, based on a dual-slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare output mode, the output compare (ocnx) is cleared on the compare match between tcntn and ocrnx while upcounting, and set on the compare match while downcounting. in inverting compare output mode, the operation is inverted. the dual-slope operation gives a lower maximum operation fre- quency compared to the single-slope operation. however, due to the symmetric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. the main difference between the phase correct, and the phase and frequency correct pwm mode is the time the ocrnx register is updated by the ocrnx buffer register, (see figure 16- 8 and figure 16-9 ). the pwm resolution for the phase and frequency correct pwm mode can be defined by either icrn or ocrna. the minimum resolution allowed is 2-bit (icrn or ocrna set to 0x0003), and f ocnxpcpwm f clk_i/o 2 n top ?? ---------------------------- - =
126 7799d?avr?11/10 atmega8u2/16u2/32u2 the maximum resolution is 16-bit (icrn or ocrna set to max). the pwm resolution in bits can be calculated using the following equation: in phase and frequency correct pwm mode the counter is incremented until the counter value matches either the value in icrn (wgmn[3:0] = 8), or the value in ocrna (wgmn[3:0] = 9). the counter has then reached the top and changes the count direction. the tcntn value will be equal to top for one timer clock cycle. the timing diagram for the phase correct and frequency correct pwm mode is shown on figure 16-9 . the figure shows phase and frequency correct pwm mode when ocrna or icrn is used to define top. the tcntn value is in the timing dia- gram shown as a histogram for illustrating the dual-slope operation. the diagram includes non- inverted and inverted pwm outputs. the small horizontal line marks on the tcntn slopes repre- sent compare matches between ocrnx and tcntn. the ocnx interrupt flag will be set when a compare match occurs. figure 16-9. phase and frequency correct pwm mode, timing diagram the timer/counter overflow flag (tovn) is set at the same timer clock cycle as the ocrnx registers are updated with the double buffer value (at bottom). when either ocrna or icrn is used for defining the top value, the ocna or icfn flag set when tcntn has reached top. the interrupt flags can then be used to generate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcntn and the ocrnx. as figure 16-9 shows the output generated is, in contrast to the phase correct mode, symmetri- cal in all periods. since the ocrnx registers ar e updated at bottom, the length of the rising and the falling slopes will always be equal. this gives symmetrical output pulses and is therefore frequency correct. r pfcpwm top 1 + ?? log 2 ?? log ---------------------------------- - = ocrnx/top updateand tovn interrupt flag set (interrupt on bottom) ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 2 3 4 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
127 7799d?avr?11/10 atmega8u2/16u2/32u2 using the icrn register for defining top works well when using fixed top values. by using icrn, the ocrna register is free to be used for generating a pwm output on ocna. however, if the base pwm frequency is actively changed by changing the top value, using the ocrna as top is clearly a better choice due to its double buffer feature. in phase and frequency correct pwm mode, the compare units allow generation of pwm wave- forms on the ocnx pins. setting the comnx[1:0] bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the comnx1:0 to three (see table 16- 3 on page 131 ). the actual ocnx value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_ocnx). the pwm waveform is generated by setting (or clear- ing) the ocnx register at the compare match between ocrnx and tcntn when the counter increments, and clearing (or setting) the ocnx register at compare match between ocrnx and tcntn when the counter decrements. the pwm frequency for the output when using phase and frequency correct pwm can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocrnx register represents special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocrnx is set equal to bottom the output will be continuously low and if set equal to top the output will be set to high for non- inverted pwm mode. for inverted pwm the output will have the opposite logic values. if ocr1a is used to define the top value (wgm1[3:0] = 9) and com1a[1:0] = 1, the oc1a output will tog- gle with a 50% duty cycle. 16.10 timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk tn ) is therefore shown as a clock enable signal in the following figures. the figures include information on when interrupt flags are set, and when the ocrnx register is updated with the ocrnx buffer value (only for modes utilizing double buffering). figure 16-10 shows a timing diagram for the setting of ocfnx. figure 16-10. timer/counter timing diagram, setting of ocfnx, no prescaling figure 16-11 shows the same timing data, but with the prescaler enabled. f ocnxpfcpwm f clk_i/o 2 n top ?? ---------------------------- - = clk tn (clk i/o /1) ocfnx clk i/o ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2
128 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 16-11. timer/counter timing diagram, setting of ocfnx, with prescaler (f clk_i/o /8) figure 16-12 shows the count sequence close to top in various modes. when using phase and frequency correct pwm mode the ocrnx register is updated at bottom. the timing diagrams will be the same, but top should be replace d by bottom, top-1 by bottom+1 and so on. the same renaming applies for modes that set the tovn flag at bottom. figure 16-12. timer/counter timing diagram, no prescaling figure 16-13 shows the same timing data, but with the prescaler enabled. ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o /8) tovn (fpwm) and icfn (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk tn (clk i/o /1) clk i/o
129 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 16-13. timer/counter timing diagram, with prescaler (f clk_i/o /8) 16.11 register description 16.11.1 tccr1a ? timer/counter1 control register a ? bit 7:6 ? comna1:0: compare output mode for channel a ? bit 5:4 ? comnb1:0: compare output mode for channel b ? bit 3:2 ? comnc1:0: compare output mode for channel c the comna[1:0], comnb[1:0], and comnc[1:0] control the output compare pins (ocna, ocnb, and ocnc respectively) behavior. if one or both of the comna[1:0] bits are written to one, the ocna output overrides the normal port func tionality of the i/o pin it is connected to. if one or both of the comnb[1:0] bits are written to one, the ocnb output overrides the normal port functionality of the i/o pin it is connected to. if one or both of the comnc[1:0] bits are writ- ten to one, the ocnc output overrides the normal port functionality of the i/o pin it is connected to. however, note that the data direction register (ddr) bit corresponding to the ocna, ocnb or ocnc pin must be set in order to enable the output driver. when the ocna, ocnb or ocnc is connected to the pin, the function of the comnx[1:0] bits is dependent of the wgmn[3:0] bits setting. table 16-1 shows the comnx[1:0] bit functionality when the wgmn[3:0] bits are set to a normal or a ctc mode (non-pwm). tovn (fpwm) and icf n (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8) bit 76543210 (0x80) com1a1 com1a0 com1b1 com1b0 com1c1 com1c0 wgm11 wgm10 tccr1a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000
130 7799d?avr?11/10 atmega8u2/16u2/32u2 . table 16-2 shows the comnx[1:0] bit functionality when the wgmn[3:0] bits are set to the fast pwm mode. note: a special case occurs when ocrna/ocrnb/ocrnc equals top and comna1/comnb1/comnc1 is set. in this case the compare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 97. for more details. table 16-3 shows the comnx[1:0] bit functionality when the wgmn[3:0] bits are set to the phase correct and frequency correct pwm mode. table 16-1. compare output mode, non-pwm comna1/comnb1/ comnc1 comna0/comnb0/ comnc0 description 00 normal port operation, ocna/ocnb/ocnc disconnected. 0 1 toggle ocna/ocnb/ocnc on compare match. 10 clear ocna/ocnb/ocnc on compare match (set output to low level). 11 set ocna/ocnb/ocnc on compare match (set output to high level). table 16-2. compare output mode, fast pwm comna1/comnb1/ comnc0 comna0/comnb0/ comnc0 description 00 normal port operation, ocna/ocnb/ocnc disconnected. 01 wgm1[3:0] = 14 or 15: toggle oc1a on compare match, oc1b and oc1c disconnected (normal port operation). for all other wgm1 settings, normal port operation, oc1a/oc1b/oc1c disconnected. 10 clear ocna/ocnb/ocnc on compare match, set ocna/ocnb/ocnc at top 11 set ocna/ocnb/ocnc on compare match, clear ocna/ocnb/ocnc at top
131 7799d?avr?11/10 atmega8u2/16u2/32u2 note: a special case occurs when ocrna/ocrnb/ocrnc equals top and comna1/comnb1//comnc1 is set. see ?phase correct pwm mode? on page 99. for more details. ? bit 1:0 ? wgmn1:0: waveform generation mode combined with the wgmn[3:2] bits found in the tccrnb register, these bits control the count- ing sequence of the counter, the source for maximum (top) counter value, and what type of waveform generation to be used, see table 16-4 . modes of operation supported by the timer/counter unit are: normal mode (counter), clear timer on compare match (ctc) mode, and three types of pulse width modulation (pwm) modes. ( see ?modes of operation? on page 96. ). table 16-3. compare output mode, phase correct and phase and frequency correct pwm comna1/comnb/ comnc1 comna0/comnb0/ comnc0 description 00 normal port operation, ocna/ocnb/ocnc disconnected. 01 wgm1[3:0] = 8, 9 10 or 11: toggle oc1a on compare match, oc1b and oc1c disconnected (normal port operation). for all other wgm1 settings, normal port operation, oc1a/oc1b/oc1c disconnected. 10 clear ocna/ocnb/ocnc on compare match when up-counting. set ocna/ocnb/ocnc on compare match when downcounting. 11 set ocna/ocnb/ocnc on compare match when up-counting. clear ocna/ocnb/ocnc on compare match when downcounting.
132 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. the ctcn and pwmn1:0 bit definition names are obsolete. use the wgm n2:0 definitions. however, the functionality and location of these bits are compatible with previous versions of the timer. table 16-4. waveform generation mode bit description (1) mode wgmn3 wgmn2 (ctcn) wgmn1 (pwmn1) wgmn0 (pwmn0) timer/counter mode of operation top update of ocrn x at tovn flag set on 0 0 0 0 0 normal 0xffff immediate max 1 0 0 0 1 pwm, phase correct, 8-bit 0x00ff top bottom 2 0 0 1 0 pwm, phase correct, 9-bit 0x01ff top bottom 3 0 0 1 1 pwm, phase correct, 10-bit 0x03ff top bottom 4 0 1 0 0 ctc ocrna immediate max 5 0 1 0 1 fast pwm, 8-bit 0x00ff top top 6 0 1 1 0 fast pwm, 9-bit 0x01ff top top 7 0 1 1 1 fast pwm, 10-bit 0x03ff top top 81 0 0 0 pwm, phase and frequency correct icrn bottom bottom 91 0 0 1 pwm, phase and frequency correct ocrna bottom bottom 10 1 0 1 0 pwm, phase correct icrn top bottom 11 1 0 1 1 pwm, phase correct ocrna top bottom 12 1 1 0 0 ctc icrn immediate max 13 1 1 0 1 (reserved) ? ? ? 14 1 1 1 0 fast pwm icrn top top 15 1 1 1 1 fast pwm ocrna top top
133 7799d?avr?11/10 atmega8u2/16u2/32u2 16.11.2 tccr1b ? timer/counter1 control register b ? bit 7 ? icncn: input capture noise canceler setting this bit (to one) activates the input capture noise canceler. when the noise canceler is activated, the input from the input capture pin (icpn) is filtered. the filter function requires four successive equal valued samples of the icpn pin for changing its output. the input capture is therefore delayed by four oscillator cycles when the noise canceler is enabled. ? bit 6 ? icesn: input capture edge select this bit selects which edge on the input capture pin (icpn) that is used to trigger a capture event. when the icesn bit is written to zero, a falling (negative) edge is used as trigger, and when the icesn bit is written to one, a rising (positive) edge will trigger the capture. when a capture is triggered according to the icesn setting, the counter value is copied into the input capture register (icrn). the event will also set the input capture flag (icfn), and this can be used to cause an input capture interrupt, if this interrupt is enabled. when the icrn is used as top value (see description of the wgmn[3:0] bits located in the tccrna and the tccrnb register), the icpn is disconnected and consequently the input cap- ture function is disabled. ? bit 5 ? reserved bit this bit is reserved for future use. for ensuring compatibility with future devices, this bit must be written to zero when tccrnb is written. ? bit 4:3 ? wgmn[3:2]: waveform generation mode see tccrna register description. ? bit 2:0 ? csn[2:0]: clock select the three clock select bits select the clock source to be used by the timer/counter, see figure 15-1 and figure 15-2 . bit 76543210 (0x81) icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 tccr1b read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 16-5. clock select bit description csn2 csn1 csn0 description 0 0 0 no clock source. (timer/counter stopped) 0 0 1 clk i/o /1 (no prescaling 0 1 0 clk i/o /8 (from prescaler) 0 1 1 clk i/o /64 (from prescaler) 1 0 0 clk i/o /256 (from prescaler) 1 0 1 clk i/o /1024 (from prescaler) 1 1 0 external clock source on tn pin. clock on falling edge 1 1 1 external clock source on tn pin. clock on rising edge
134 7799d?avr?11/10 atmega8u2/16u2/32u2 if external pin modes are used for the timer/countern, transitions on the tn pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. 16.11.3 tccr1c ? timer/counter1 control register c ? bit 7 ? focna: force output compare for channel a ? bit 6 ? focnb: force output compare for channel b ? bit 5 ? focnc: force output compare for channel c the focna/focnb/focnc bits are only active when the wgmn[3:0] bits specifies a non-pwm mode. when writing a logical one to the focna/focnb/focnc bit, an immediate compare match is forced on the waveform generation unit. the ocna/ocnb/ocnc output is changed according to its comnx[1:0] bits setting. note that the focna/focnb/focnc bits are imple- mented as strobes. therefore it is the value present in the comnx1:0 bits that determine the effect of the forced compare. a focna/focnb/focnc strobe will not generate any interrupt nor will it clear the timer in clear timer on compare match (ctc) mode using ocrna as top. the focna/focnb/focnb bits are always read as zero. ? bit 4:0 ? res: reserved bits these bits are reserved for future use. for ensuring compatibility with future devices, these bits must be written to zero when tccrnc is written. 16.11.4 tcnt1h and tcnt1l ? timer/counter1 the two timer/counter i/o locations (tcntnh and tcntnl, combined tcntn) give direct access, both for read and for write operations, to the timer/counter unit 16-bit counter. to ensure that both the high and low bytes are read and written simultaneously when the cpu accesses these registers, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 110. modifying the counter (tcntn) while the counter is running introduces a risk of missing a com- pare match between tcntn and one of the ocrnx registers. writing to the tcntn register blocks (removes) the compare match on the following timer clock for all compare units. bit 76543210 (0x82) foc1a foc1b foc1c ? ? ? ? ? tccr1c read/write w w w r r r r r initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x85) tcnt1[15:8] tcnt1h (0x84) tcnt1[7:0] tcnt1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
135 7799d?avr?11/10 atmega8u2/16u2/32u2 16.11.5 ocr1ah and ocr1al ? output compare register 1 a 16.11.6 ocr1bh and ocr1bl ? output compare register 1 b 16.11.7 ocr1ch and ocr1cl ? output compare register 1 c the output compare registers contain a 16-bit value that is continuously compared with the counter value (tcntn). a match can be used to generate an output compare interrupt, or to generate a waveform output on the ocnx pin. the output compare registers are 16-bit in size. to ensure that both the high and low bytes are written simultaneously when the cpu writes to these registers, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 110. 16.11.8 icr1h and icr1l ? input capture register 1 ithe input capture is updated with the counter (tcntn) value each time an event occurs on the icpn pin (or optionally on the analog comparator output for timer/counter1). the input capture can be used for defining the counter top value. the input capture register is 16-bit in size. to ensure that both the high and low bytes are read simultaneously when the cpu accesses these registers, the access is performed using an 8-bit temporary high byte register (temp). this temporar y register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 110. 16.11.9 timsk1 ? timer/counter1 interrupt mask register bit 76543210 (0x89) ocr1a[15:8] ocr1ah (0x88) ocr1a[7:0] ocr1al read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x8b) ocr1b[15:8] ocr1bh (0x8a) ocr1b[7:0] ocr1bl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x8d) ocr1c[15:8] ocr1ch (0x8c) ocr1c[7:0] ocr1cl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x87) icr1[15:8] icr1h (0x86) icr1[7:0] icr1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x6f) ? ? icie1 ? ocie1c ocie1b ocie1a toie1 timsk1 read/write r r r/w r r/w r/w r/w r/w initial value 00000000
136 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 5 ? icien: timer/countern, input capture interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/countern input capture interrupt is enabled. the corresponding interrupt vector ( see ?interrupts? on page 64. ) is executed when the icfn flag, located in tifrn, is set. bit 3 ? ocienc: timer/countern, output compare c match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/countern output compare c match interrupt is enabled. the corresponding interrupt vector ( see ?interrupts? on page 64. ) is executed when the ocfnc flag, located in tifrn, is set. ? bit 2 ? ocienb: timer/countern, output compare b match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/countern output compare b match interrupt is enabled. the corresponding interrupt vector ( see ?interrupts? on page 64. ) is executed when the ocfnb flag, located in tifrn, is set. ? bit 1 ? ociena: timer/countern, output compare a match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/countern output compare a match interrupt is enabled. the corresponding interrupt vector ( see ?interrupts? on page 64. ) is executed when the ocfna flag, located in tifrn, is set. ? bit 0 ? toien: timer/countern, overflow interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/countern overflow interrupt is enabled. the corresponding interrupt vector ( see ?interrupts? on page 64. ) is executed when the tovn flag, located in tifrn, is set. 16.11.10 tifr1 ? timer/counter1 interrupt flag register ? bit 5 ? icfn: timer/countern, input capture flag this flag is set when a capture event occurs on the icpn pin. when the input capture register (icrn) is set by the wgmn[3:0] to be used as the top value, the icfn flag is set when the counter reaches the top value. icfn is automatically cleared when the input capture interrupt vector is executed. alternatively, icfn can be cleared by writing a logic one to its bit location. ? bit 3 ? ocfnc: timer/countern, output compare c match flag this flag is set in the timer clock cycle after the counter (tcntn) value matches the output compare register c (ocrnc). note that a forced output compare (focnc) strobe will not set the ocfnc flag. ocfnc is automatically cleared when the output compare match c interrupt vector is exe- cuted. alternatively, ocfnc can be cleared by writing a logic one to its bit location. bit 76543210 0x16 (0x36) ? ? icf1 ? ocf1c ocf1b ocf1a tov1 tifr1 read/write r r r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
137 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 2 ? ocfnb: timer/counter1, output compare b match flag this flag is set in the timer clock cycle after the counter (tcntn) value matches the output compare register b (ocrnb). note that a forced output compare (focnb) strobe will not set the ocfnb flag. ocfnb is automatically cleared when the output compare match b interrupt vector is exe- cuted. alternatively, ocfnb can be cleared by writing a logic one to its bit location. ? bit 1 ? ocf1a: timer/counter1, output compare a match flag this flag is set in the timer clock cycle after the counter (tcntn value matches the output com- pare register a (ocrna). note that a forced output compare (focna) strobe will not set the ocfna flag. ocfna is automatically cleared when the output compare match a interrupt vector is exe- cuted. alternatively, ocfna can be cleared by writing a logic one to its bit location. ? bit 0 ? tovn: timer/countern, overflow flag the setting of this flag is dependent of the wgmn[3:0] bits setting. in normal and ctc modes, the tovn flag is set when the timer overflows. refer to table 16-4 on page 132 for the tovn flag behavior when using another wgmn[3:0] bit setting. tovn is automatically cleared when the timer/countern overflow interrupt vector is executed. alternatively, tovn can be cleared by writing a logic one to its bit location.
138 7799d?avr?11/10 atmega8u2/16u2/32u2 17. spi ? serial peripheral interface 17.1 features ? full-duplex, three-wire synchronous data transfer ? master or slave operation ? lsb first or msb first data transfer ? seven programmable bit rates ? end of transmission interrupt flag ? write collision flag protection ? wake-up from idle mode ? double speed (ck/2) master spi mode 17.2 overview the serial peripheral interface (spi) allows high-speed synchronous data transfer between the atmega8u2/16u2/32u2 and peripheral devices or between several avr devices. usart can also be used in master spi mode, see ?usart in spi mode? on page 176. the power reduction spi bit, prspi, in ?minimizing power consumption? on page 44 on page 50 must be written to zero to enable spi module. figure 17-1. spi block diagram (1) note: 1. refer to figure 1-1 on page 2 , and table 12-6 on page 77 for spi pin placement. spi2x spi2x divider /2/4/8/16/32/64/128
139 7799d?avr?11/10 atmega8u2/16u2/32u2 the interconnection between master and slave cpus with spi is shown in figure 17-2 . the sys- tem consists of two shift registers, and a master clock generator. the spi master initiates the communication cycle when pulling low the slave select ss pin of the desired slave. master and slave prepare the data to be sent in their res pective shift registers, and the master generates the required clock pulses on the sck line to interchange data. data is always shifted from mas- ter to slave on the master out ? slave in, mosi, line, and from slave to master on the master in ? slave out, miso, line. after each data packet, the master will synchronize the slave by pulling high the slave select, ss, line. when configured as a master, the spi interface has no automatic control of the s s line. this must be handled by user software before communication can start. when this is done, writing a byte to the spi data register starts the spi cl ock generator, and the hardware shifts the eight bits into the slave. after shifting one byte, the spi clock generator stops, setting the end of transmission flag (spif). if the spi interrupt enable bit (spie) in the spcr register is set, an interrupt is requested. the master may continue to shift the next byte by writing it into spdr, or signal the end of packet by pulling high the slave select, ss line. the last incoming byte will be kept in the buffer register for later use. when configured as a slave, the spi interface will remain sleeping with miso tri-stated as long as the s s pin is driven high. in this state, software may update the contents of the spi data register, spdr, but the data will not be shifted out by incoming clock pulses on the sck pin until the ss pin is driven low. as one byte has been completely shifted, the end of transmission flag, spif is set. if the spi interrupt enable bit, spie, in the spcr register is set, an interrupt is requested. the slave may continue to place new data to be sent into spdr before reading the incoming data. the last incoming byte will be kept in the buffer register for later use. figure 17-2. spi master-slave interconnection the system is single buffered in the transmit direction and double buffered in the receive direc- tion. this means that bytes to be transmitted cannot be written to the spi data register before the entire shift cycle is completed. when receiving data, however, a received character must be read from the spi data register before the next character has been completely shifted in. oth- erwise, the first byte is lost. in spi slave mode, the control logic will sample the incoming signal of the sck pin. to ensure correct sampling of the clock signal, the frequency of the spi clock should never exceed f osc /4. when the spi is enabled, the data direction of the mosi, miso, sck, and ss pins is overridden according to table 17-1 . for more details on automatic port overrides, refer to ?alternate port shift enable
140 7799d?avr?11/10 atmega8u2/16u2/32u2 functions? on page 72 . note: 1. see ?alternate functions of port b? on page 74 for a detailed description of how to define the direction of the user defined spi pins. the following code examples show how to initialize the spi as a master and how to perform a simple transmission. ddr_spi in the examples mu st be replaced by the actual data direction register controlling the spi pins. dd_mosi, dd_mis o and dd_sck must be replaced by the actual data direction bits for these pins. e.g. if mosi is placed on pin pb5, replace dd_mosi with ddb5 and ddr_spi with ddrb. table 17-1. spi pin overrides (1) pin direction, master spi direction, slave spi mosi user defined input miso input user defined sck user defined input ss user defined input
141 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. see ?code examples? on page 6. assembly code example (1) spi_masterinit: ; set mosi and sck output, all others input ldi r17,(1< 142 7799d?avr?11/10 atmega8u2/16u2/32u2 the following code examples show how to initialize the spi as a slave and how to perform a simple reception. note: 1. see ?code examples? on page 6. 17.3 ss pin functionality 17.3.1 slave mode when the spi is configured as a slave, the slave select ( s s ) pin is always input. when s s is held low, the spi is activated, and miso becomes an output if configured so by the user. all other pins are inputs. when ss is driven high, all pins are inputs, and the spi is passive, which assembly code example (1) spi_slaveinit: ; set miso output, all others input ldi r17,(1< 143 7799d?avr?11/10 atmega8u2/16u2/32u2 means that it will not receive incoming data. note that the spi logic will be reset once the ss pin is driven high. the s s pin is useful for packet/byte synchronizatio n to keep the slave bit counter synchronous with the master clock generator. when the s s pin is driven high, the spi slave will immediately reset the send and receive logic, and drop any partially received data in the shift register. 17.3.2 master mode when the spi is configured as a master (mstr in spcr is set), the user can determine the direction of the ss pin. if s s is configured as an output, the pin is a general output pin which does not affect the spi system. typically, the pin will be driving the ss pin of the spi slave. if ss is configured as an input, it must be held high to ensure master spi operation. if the ss pin is driven low by peripheral circuitry when the spi is configured as a master with the s s pin defined as an input, the spi system interprets this as another master selecting the spi as a slave and starting to send data to it. to avoid bus contention, the spi system takes the following actions: 1. the mstr bit in spcr is cleared and the spi system becomes a slave. as a result of the spi becoming a slave, the mosi and sck pins become inputs. 2. the spif flag in spsr is set, and if the spi interrupt is enabled, and the i-bit in sreg is set, the interrupt routine will be executed. thus, when interrupt-driven spi transmission is used in master mode, and there exists a possi- bility that ss is driven low, the interrupt should always check that the mstr bit is still set. if the mstr bit has been cleared by a slave select, it must be set by the user to re-enable spi master mode. 17.4 data modes there are four combinations of sck phase and polarity with respect to serial data, which are determined by control bits cpha and cpol. the spi data transfer formats are shown in figure 17-3 and figure 17-4 . data bits are shifted out and latched in on opposite edges of the sck sig- nal, ensuring sufficient time for data signals to stabilize. this is clearly seen by summarizing table 17-3 and table 17-4 , as done below:
144 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 17-3. spi transfer format with cpha = 0 figure 17-4. spi transfer format with cpha = 1 table 17-2. cpol functionality leading edge trailing edge spi mode cpol=0, cpha=0 sample (rising) setup (falling) 0 cpol=0, cpha=1 setup (rising) sample (falling) 1 cpol=1, cpha=0 sample (falling) setup (rising) 2 cpol=1, cpha=1 setup (falling) sample (rising) 3 bit 1 bit 6 lsb msb sck (cpol = 0) mode 0 sample i mosi/miso change 0 mosi pin change 0 miso pin sck (cpol = 1) mode 2 ss msb lsb bit 6 bit 1 bit 5 bit 2 bit 4 bit 3 bit 3 bit 4 bit 2 bit 5 msb first (dord = 0) lsb first (dord = 1) sck (cpol = 0) mode 1 sample i mosi/miso change 0 mosi pin change 0 miso pin sck (cpol = 1) mode 3 ss msb lsb bit 6 bit 1 bit 5 bit 2 bit 4 bit 3 bit 3 bit 4 bit 2 bit 5 bit 1 bit 6 lsb msb msb first (dord = 0) lsb first (dord = 1)
145 7799d?avr?11/10 atmega8u2/16u2/32u2 17.5 register description 17.5.1 spcr ? spi control register ? bit 7 ? spie: spi interrupt enable this bit causes the spi interrupt to be executed if spif bit in the spsr register is set and the if the global interrupt enable bit in sreg is set. ? bit 6 ? spe: spi enable when the spe bit is written to on e, the spi is enabled. this bit must be set to enable any spi operations. ? bit 5 ? dord: data order when the dord bit is written to one, the lsb of the data word is transmitted first. when the dord bit is written to zero, the msb of the data word is transmitted first. ? bit 4 ? mstr: master/slave select this bit selects master spi mode when written to one, and slave spi m ode when written logic zero. if ss is configured as an input and is driven low while mstr is set, mstr will be cleared, and spif in spsr will become set. the user will then have to set mstr to re-enable spi mas- ter mode. ? bit 3 ? cpol: clock polarity when this bit is written to one, sck is high when idle. when cpol is written to zero, sck is low when idle. refer to figure 17-3 and figure 17-4 for an example. the cpol functionality is sum- marized below: ? bit 2 ? cpha: clock phase the settings of the clock phase bit (cpha) determine if data is sampled on the leading (first) or trailing (last) edge of sck. refer to figure 17-3 and figure 17-4 for an example. the cpol functionality is summarized below: bit 76543210 0x2c (0x4c) spie spe dord mstr cpol cpha spr1 spr0 spcr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 17-3. cpol functionality cpol leading edge trailing edge 0 rising falling 1 falling rising table 17-4. cpha functionality cpha leading edge trailing edge 0 sample setup 1 setup sample
146 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bits 1, 0 ? spr1, spr0: spi clock rate select 1 and 0 these two bits control the sck rate of the device configured as a master. spr1 and spr0 have no effect on the slave. the relationship between sck and the oscillator clock frequency f osc is shown in the following table: 17.5.2 spsr ? spi status register ? bit 7 ? spif: spi interrupt flag when a serial transfer is complete, the spif flag is set. an interrupt is generated if spie in spcr is set and global interrupts are enabled. if ss is an input and is driven low when the spi is in master mode, this will also set the spif flag. spif is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, the spif bit is cleared by first reading the spi status register with spif set, then accessing the spi data register (spdr). ? bit 6 ? wcol: write collision flag the wcol bit is set if the spi data register (spdr) is written during a data transfer. the wcol bit (and the spif bit) are cleared by first reading the spi status register with wcol set, and then accessing the spi data register. ? bit 5:1 ? res: reserved bits these bits are reserved bits in the atmega8u2/16u2/32u2 and will always read as zero. ? bit 0 ? spi2x: double spi speed bit when this bit is written logic one the spi speed (sck frequency) will be doubled when the spi is in master mode (see table 17-5 ). this means that the minimum sck period will be two cpu clock periods. when the spi is configured as slave, the spi is only guaranteed to work at f osc /4 or lower. the spi interface on the atmega8u2/16u2/32u2 is also used for program memory and eeprom downloading or uploading. see page 259 for serial programming and verification. table 17-5. relationship between sck and the oscillator frequency spi2x spr1 spr0 sck frequency 000 f osc / 4 001 f osc / 16 010 f osc / 64 011 f osc / 128 100 f osc / 2 101 f osc / 8 110 f osc / 32 111 f osc / 64 bit 76543210 0x2d (0x4d) spif wcol ? ? ? ? ? spi2x spsr read/write r r r r r r r r/w initial value 0 0 0 0 0 0 0 0
147 7799d?avr?11/10 atmega8u2/16u2/32u2 17.5.3 spdr ? spi data register the spi data register is a read/write register used for data transfer between the register file and the spi shift register. writing to the register initiates data transmission. reading the regis- ter causes the shift register receive buffer to be read. bit 76543210 0x2e (0x4e) msb??????lsb spdr read/write r/w rrrrrrr/w initial value xxxxxxxx undefined
148 7799d?avr?11/10 atmega8u2/16u2/32u2 18. usart 18.1 features ? full duplex operation (independent serial receive and transmit registers) ? asynchronous or synchronous operation ? flow control cts/rts signals hardware management ? master or slave clocked synchronous operation ? high resolution baud rate generator ? supports serial frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits ? odd or even parity generation and parity check supported by hardware ? data overrun detection ? framing error detection ? noise filtering includes false start bit detection and digital low pass filter ? three separate interrupts on tx complete, tx data register empty and rx complete ? multi-processor communication mode ? double speed asynchronous communication mode 18.2 overview the universal synchronous and asynchronous serial receiver and transmitter (usart) is a highly flexible serial communication device. a simplified block diagram of the usart transmitter is shown in figure 18-1 on page 149 . cpu accessible i/o registers and i/o pins are shown in bold.
149 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 18-1. usart block diagram (1) note: 1. see figure 1-1 on page 2 , table 12-9 on page 79 and for usart pin placement. the dashed boxes in the block diagram separate the three main parts of the usart (listed from the top): clock generator, transmitter and receiv er. control registers are shared by all units. the clock generation logic consists of synchronization logic for external clock input used by synchronous slave operation, and the baud rate generator. the xckn (transfer clock) pin is only used by synchronous transfer mode. the transmitter consists of a single write buffer, a serial shift register, parity generator and control logic for handling different serial frame for- mats. the write buffer allows a continuous transfer of data without any delay between frames. the receiver is the most complex part of the usart module due to its clock and data recovery units. the recovery units are used for asynchronous data reception. in addition to the recovery units, the receiver includes a parity checker, control logic, a shift register and a two level receive buffer (udrn). the receiver supports the same frame formats as the transmitter, and can detect frame error, data overrun and parity errors. 18.3 clock generation the clock generation logic generates the base clock for the transmitter and receiver. the usartn supports four modes of clock operation: normal asynchronous, double speed asyn- chronous, master synchronous and slave synchronous mode. the umseln bit in usart control and status register c (ucsrnc) selects between asynchronous and synchronous operation. double speed (asynchronous mode only) is controlled by the u2xn found in the ucsrna register. when using synchronous mode (umseln = 1), the data direction register parity generator ubrr[h:l] udr (transmit) ucsra ucsrb ucsrc baud rate generator transmit shift register receive shift register rxd txd pin control udr (receive) pin control xck data recovery clock recovery pin control tx control rx control parity checker data bus osc sync logic clock generator transmitter receiver
150 7799d?avr?11/10 atmega8u2/16u2/32u2 for the xckn pin (ddr_xckn) controls whether the clock source is internal (master mode) or external (slave mode). the xckn pin is only active when using synchronous mode. figure 18-2 shows a block diagram of the clock generation logic. figure 18-2. clock generation logic, block diagram signal description: 18.3.1 internal clock generation ? the baud rate generator internal clock generation is used for the asynchronous and the synchronous master modes of operation. the description in this section refers to figure 18-2 . the usart baud rate register (ubrrn) and the down-counter connected to it function as a programmable prescaler or baud rate generator. the down-counter, running at system clock (f osc ), is loaded with the ubrrn value each time the counter has counted down to zero or when the ubrrln register is written. a clock is generated each time the counter reaches zero. this clock is the baud rate generator clock output (= f osc /(ubrrn+1)). the transmitter divides the baud rate generator clock output by 2, 8 or 16 depending on mode. the baud rate generator out- put is used directly by the receiver?s clock and data recovery units. however, the recovery units use a state machine that uses 2, 8 or 16 states depending on mode set by the state of the umseln, u2xn and ddr_xckn bits. txclk transmitter clock (internal signal). rxclk receiver base clock (internal signal). xcki input from xck pin (internal signal). used for synchronous slave operation. xcko clock output to xck pin (internal signal). used for synchronous master operation. f osc xtal pin frequency (system clock). prescaling down-counter /2 ubrr /4 /2 fosc ubrr+1 sync register osc xck pin txclk u2x umsel ddr_xck 0 1 0 1 xcki xcko ddr_xck rxclk 0 1 1 0 edge detector ucpol
151 7799d?avr?11/10 atmega8u2/16u2/32u2 table 18-1 contains equations for calculating the baud rate (in bits per second) and for calculat- ing the ubrrn value for each mode of operation using an internally generated clock source. note: 1. the baud rate is defined to be the transfer rate in bit per second (bps) baud baud rate (in bits per second, bps) f osc system oscillator clock frequency ubrrn contents of the ubrrhn and ubrrln registers, (0-4095) some examples of ubrrn values for some system clock frequencies are found in table 18-9 on page 172 . 18.3.2 double speed operation (u2xn) the transfer rate can be doubled by setting the u2xn bit in ucsrna. setting this bit only has effect for the asynchronous operation. set this bit to zero when using synchronous operation. setting this bit will reduce the di visor of the baud rate divider fr om 16 to 8, effectively doubling the transfer rate for asynchronous communication. note however that the receiver will in this case only use half the number of samples (reduced from 16 to 8) for data sampling and clock recovery, and therefore a more accurate baud rate setting and system clock are required when this mode is used. for the transmitter, there are no downsides. table 18-1. equations for calculating baud rate register setting operating mode equation for calculating baud rate (1) equation for calculating ubrr value asynchronous normal mode (u2xn = 0) asynchronous double speed mode (u2xn = 1) synchronous master mode baud f osc 16 ubrr n 1 + ?? ----------------------------------------- - = ubrr n f osc 16 baud ----------------------- - 1 ? = baud f osc 8 ubrr n 1 + ?? -------------------------------------- - = ubrr n f osc 8 baud -------------------- 1 ? = baud f osc 2 ubrr n 1 + ?? -------------------------------------- - = ubrr n f osc 2 baud -------------------- 1 ? =
152 7799d?avr?11/10 atmega8u2/16u2/32u2 18.3.3 external clock external clocking is used by the synchronous sl ave modes of operation. the description in this section refers to figure 18-2 for details. external clock input from the xckn pin is sampled by a synchronization register to minimize the chance of meta-stability. the output from the synchronization register must then pass through an edge detector before it can be used by the transmitter and receiver. this process intro- duces a two cpu clock period delay and therefore the maximum external xckn clock frequency is limited by the following equation: note that f osc depends on the stability of the system clock source. it is therefore recommended to add some margin to avoid possible loss of data due to frequency variations. 18.3.4 synchronous clock operation when synchronous mode is used (umseln = 1), the xckn pin will be used as either clock input (slave) or clock output (master). the dependency between the clock edges and data sampling or data change is the same. the basic principle is that data input (on rxdn) is sampled at the opposite xckn clock edge of the edge the data output (txdn) is changed. figure 18-3. synchronous mode xckn timing. the ucpoln bit ucrsc selects which xckn clock edge is used for data sampling and which is used for data change. as figure 18-3 shows, when ucpoln is zero the data will be changed at rising xckn edge and sampled at falling xckn edge. if ucpoln is set, the data will be changed at falling xckn edge and sampled at rising xckn edge. 18.4 frame formats a serial frame is defined to be one character of data bits with synchronization bits (start and stop bits), and optionally a parity bit for error checking. the usart accepts all 30 combinations of the following as valid frame formats: ? 1 start bit ? 5, 6, 7, 8, or 9 data bits ? no, even or odd parity bit ? 1 or 2 stop bits f xck f os c 4 ------------ - - ? rxd / txd xck rxd / txd xck ucpol = 0 ucpol = 1 sample sample
153 7799d?avr?11/10 atmega8u2/16u2/32u2 a frame starts with the start bit followed by the least significant data bit. then the next data bits, up to a total of nine, are succeeding, ending with the most significant bit. if enabled, the parity bit is inserted after the data bits, before the stop bits. when a complete frame is transmitted, it can be directly followed by a new frame, or the communication line can be set to an idle (high) state. figure 18-4 illustrates the possible combinations of th e frame formats. bits inside brackets are optional. figure 18-4. frame formats st start bit, always low. (n) data bits (0 to 8). p parity bit. can be odd or even. sp stop bit, always high. idle no transfers on the communication line (rxdn or txdn). an idle line must be high. the frame format used by the usart is set by the ucszn2:0, upmn1:0 and usbsn bits in ucsrnb and ucsrnc. the receiver and transmitter use the same setting. note that changing the setting of any of these bits will corrupt all ongoing communication for both the receiver and transmitter. the usart character size (ucszn2:0) bits select the number of data bits in the frame. the usart parity mode (upmn1:0) bits enable and set the type of parity bit. the selection between one or two stop bits is done by the usart stop bit select (usbsn) bit. the receiver ignores the second stop bit. an fe (frame error) will therefore only be detected in the cases where the first stop bit is zero. 18.4.1 parity bit calculation the parity bit is calculated by doing an exclusive-or of all the data bits. if odd parity is used, the result of the exclusive or is inverted. the relation between the parity bit and data bits is as follows:: p even parity bit using even parity p odd parity bit using odd parity d n data bit n of the character if used, the parity bit is located between the last data bit and first stop bit of a serial frame. 1 0 2 3 4 [5] [6] [7] [8] [p] st sp1 [sp2] (st / idle) (idle) frame p even d n 1 ? ? d 3 d 2 d 1 d 0 0 p odd ?????? d n 1 ? ? d 3 d 2 d 1 d 0 1 ?????? = =
154 7799d?avr?11/10 atmega8u2/16u2/32u2 18.5 usart initialization the usart has to be initialized before any communication can take place. the initialization pro- cess normally consists of setting the baud rate, setting frame format and enabling the transmitter or the receiver depending on the usage. for interrupt driven usart operation, the global interrupt flag should be cleared (and interrupts globally disabled) when doing the initialization. before doing a re-initialization with changed baud rate or frame format, be sure that there are no ongoing transmissions during the period the registers are changed. the txcn flag can be used to check that the transmitter has completed all transfers, and the rxc flag can be used to check that there are no unread data in the receive buffer. note that the txcn flag must be cleared before each transmission (before udrn is written) if it is used for this purpose. the following simple usart initialization code examples show one assembly and one c func- tion that are equal in functionality. the examples assume asynchronous operation using polling (no interrupts enabled) and a fixed frame format. the baud rate is given as a function parameter. for the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers. note: 1. see ?code examples? on page 6. more advanced initialization routines can be made that include frame format as parameters, dis- able interrupts and so on. however, many applications use a fixed setting of the baud and control registers, and for these types of applications the initialization code can be placed directly in the main routine, or be combined with initialization code for other i/o modules. assembly code example (1) usart_init: ; set baud rate out ubrrhn, r17 out ubrrln, r16 ; enable receiver and transmitter ldi r16, (1<>8); ubrrln = ( unsigned char )baud; /* enable receiver and transmitter */ ucsrnb = (1< 155 7799d?avr?11/10 atmega8u2/16u2/32u2 18.6 data transmission ? the usart transmitter the usart transmitter is enabled by setting the transmit enable (txen) bit in the ucsrnb register. when the transmitter is enabled, the normal port operation of the txdn pin is overrid- den by the usart and given the function as the transmitter?s serial output. the baud rate, mode of operation and frame format must be set up once before doing any transmissions. if syn- chronous operation is used, the clock on the xckn pin will be overridden and used as transmission clock. 18.6.1 sending frames with 5 to 8 data bit a data transmission is initiated by loading the transmit buffer with the data to be transmitted. the cpu can load the transmit buffer by writing to the udrn i/o location. the buffered data in the transmit buffer will be moved to the shift register when the shift register is ready to send a new frame. the shift register is loaded with new data if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previous frame is transmitted. when the shift register is loaded with new data, it will transfer one complete frame at the rate given by the baud register, u2xn bit or by xckn depending on mode of operation. the following code examples show a simple usart transmit function based on polling of the data register empty (udren) flag. when using frames with less than eight bits, the most sig- nificant bits written to the udrn are ignored. the usart has to be initialized before the function can be used. for the assembly code, the data to be sent is assumed to be stored in register r16 note: 1. see ?code examples? on page 6. the function simply waits for the transmit buffer to be empty by checking the udren flag, before loading it with new data to be transmitted. if the data register empty interrupt is utilized, the interrupt routine writes the data into the buffer. 18.6.2 sending frames with 9 data bit if 9-bit characters are used (ucs zn = 7), the ninth bit must be written to the txb8 bit in ucs- rnb before the low byte of the character is written to udrn. the following code examples show assembly code example (1) usart_transmit: ; wait for empty transmit buffer sbis ucsrna,udren rjmp usart_transmit ; put data (r16) into buffer, sends the data out udrn,r16 ret c code example (1) void usart_transmit( unsigned char data ) { /* wait for empty transmit buffer */ while ( !( ucsrna & (1< 156 7799d?avr?11/10 atmega8u2/16u2/32u2 a transmit function that handles 9-bit characters. fo r the assembly code, the data to be sent is assumed to be stored in registers r17:r16. notes: 1. these transmit functions are written to be general functions. they can be optimized if the con- tents of the ucsrnb is static. for example, only the txb8 bit of the ucsrnb register is used after initialization. 2. see ?code examples? on page 6. the ninth bit can be used for indicating an address frame when using multi processor communi- cation mode or for other protocol handling as for example synchronization. 18.6.3 transmitter flags and interrupts the usart transmitter has two flags that indicate its state: usart data register empty (udren) and transmit complete (txcn). both flags can be used for generating interrupts. the data register empty (udren) flag indicates whether the transmit buffer is ready to receive new data. this bit is set when the transmit buffer is empty, and cleared when the transmit buffer contains data to be transmitted that has not yet been moved into the shift register. for compat- ibility with future devices, always write this bit to zero when writing the ucsrna register. when the data register empty interrupt enable (udrien) bit in ucsrnb is written to one, the usart data register empty interrupt will be executed as long as udren is set (provided that global interrupts are enabled). udren is cleared by writing udrn. when interrupt-driven data transmission is used, the data register empty interrupt routine must either write new data to assembly code example (1)(2) usart_transmit: ; wait for empty transmit buffer sbis ucsrna,udren rjmp usart_transmit ; copy 9th bit from r17 to txb8 cbi ucsrnb,txb8 sbrc r17,0 sbi ucsrnb,txb8 ; put lsb data (r16) into buffer, sends the data out udrn,r16 ret c code example (1)(2) void usart_transmit( unsigned int data ) { /* wait for empty transmit buffer */ while ( !( ucsrna & (1< 157 7799d?avr?11/10 atmega8u2/16u2/32u2 udrn in order to clear udren or disable the data register empty interrupt, otherwise a new interrupt will occur once the interrupt routine terminates. the transmit complete (txcn) flag bit is set one when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer. the txcn flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txcn flag is useful in half-duplex commu- nication interfaces (like the rs-485 standard), where a transmitting application must enter receive mode and free the communication bus immediately after completing the transmission. when the transmit compete interrupt enable (txcien) bit in ucsrnb is set, the usart transmit complete interrupt will be executed when the txcn flag becomes set (provided that global interrupts are enabled). when the transmit complete interrupt is used, the interrupt han- dling routine does not have to clear the txcn flag, this is done automatically when the interrupt is executed. 18.6.4 parity generator the parity generator calculates the parity bit for the serial frame data. when parity bit is enabled (upmn1 = 1), the transmitter control logic inserts the parity bit between the last data bit and the first stop bit of the frame that is sent. 18.6.5 disabling the transmitter the disabling of the transmitter (setting the txen to zero) will not become effective until ongo- ing and pending transmissions are completed, i.e., when the transmit shift register and transmit buffer register do not contain data to be transmitted. when disabled, the transmitter will no longer override the txdn pin. 18.7 data reception ? the usart receiver the usart receiver is enabled by writing the receive enable (rxenn) bit in the ucsrnb register to one. when the receiver is enabled, the normal pin operation of the rxdn pin is overridden by the usart and given the function as the receiver?s serial input. the baud rate, mode of operation and frame format must be set up once before an y serial reception can be done. if synchronous operation is used, the clock on the xckn pin will be used as transfer clock. 18.7.1 receiving frames with 5 to 8 data bits the receiver starts data reception when it detects a valid start bit. each bit that follows the start bit will be sampled at the baud rate or xckn clock, and shifted into the receive shift register until the first stop bit of a frame is received. a second stop bit will be ignored by the receiver. when the first stop bit is received, i.e., a complete serial frame is present in the receive shift register, the contents of the shift register will be moved into the receive buffer. the receive buffer can then be read by reading the udrn i/o location. the following code example shows a simple usart receive function based on polling of the receive complete (rxcn) flag. when using frames with less than eight bits the most significant
158 7799d?avr?11/10 atmega8u2/16u2/32u2 bits of the data read from the udrn will be masked to zero. the usart has to be initialized before the function can be used. note: 1. see ?code examples? on page 6. the function simply waits for data to be present in the receive buffer by checking the rxcn flag, before reading the buffer and returning the value. 18.7.2 receiving frames with 9 data bits if 9-bit characters are used (ucszn=7) the ninth bit must be read from the rxb8n bit in ucs- rnb before reading the low bits from the udrn. this rule applies to the fen, dorn and upen status flags as well. read status from ucsrna, then data from udrn. reading the udrn i/o location will change the state of the receive buffer fifo and consequently the txb8n, fen, dorn and upen bits, which all are stored in the fifo, will change. the following code example shows a simple usart receive function that handles both nine bit characters and the status bits. assembly code example (1) usart_receive: ; wait for data to be received sbis ucsrna, rxcn rjmp usart_receive ; get and return received data from buffer in r16, udrn ret c code example (1) unsigned char usart_receive( void ) { /* wait for data to be received */ while ( !(ucsrna & (1< 159 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. see ?code examples? on page 6. the receive function example reads all the i/o registers into the register file before any com- putation is done. this gives an optimal receive buffer utilization since the buffer location read will be free to accept new data as early as possible. assembly code example (1) usart_receive: ; wait for data to be received sbis ucsrna, rxcn rjmp usart_receive ; get status and 9th bit, then data from buffer in r18, ucsrna in r17, ucsrnb in r16, udrn ; if error, return -1 andi r18,(1<> 1) & 0x01; return ((resh << 8) | resl); }
160 7799d?avr?11/10 atmega8u2/16u2/32u2 18.7.3 receive compete flag and interrupt the usart receiver has one flag that indicates the receiver state. the receive complete (rxcn) flag indicates if there are unread data present in the receive buf- fer. this flag is one when unread data exist in the receive buffer, and zero when the receive buffer is empty (i.e., does not contain any unread data). if the receiver is disabled (rxenn = 0), the receive buffer will be flushed and consequently the rxcn bit will become zero. when the receive complete interrupt enable (rxcien) in ucsrnb is set, the usart receive complete interrupt will be executed as long as the rxcn flag is set (provided that global inter- rupts are enabled). when interrupt-driven data reception is used, the receive complete routine must read the received data from udrn in order to clear the rxcn flag, otherwise a new inter- rupt will occur once the interrupt routine terminates. 18.7.4 receiver error flags the usart receiver has three error flags: frame error (fen), data overrun (dorn) and parity error (upen). all can be accessed by reading ucsrna. common for the error flags is that they are located in the receive buffer together with the frame for which they indicate the error status. due to the buffering of the error flags, the ucsrna must be read before the receive buffer (udrn), since reading the udrn i/o location changes the buffer read location. another equality for the error flags is that they ca n not be altered by software doing a write to the flag location. however, all flags must be set to zero when the ucsrna is written for upward compatibility of future usart implementations. none of the error flags can generate interrupts. the frame error (fen) flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. the fen flag is zero when the stop bit was correctly read (as one), and the fen flag will be one when the stop bit was incorrect (zero). this flag can be used for detecting out-of-sync conditions, detecting break conditions and protocol handling. the fen flag is not affected by the setting of the usbs n bit in ucsrnc since the receiver ignores all, except for the first, stop bits. for compatibility with future devices, always set this bit to zero when writing to ucsrna. the data overrun (dorn) flag indicates data loss due to a receiver buffer full condition. a data overrun occurs when the receive buffer is full (two characters), it is a new character wait- ing in the receive shift register, and a new start bit is detected. if the dorn flag is set there was one or more serial frame lost between the frame last read from udrn, and the next frame read from udrn. for compatibility with future devices, always write this bit to zero when writing to ucsrna. the dorn flag is cleared when the frame received was successfully moved from the shift register to the receive buffer. the parity error (upen) flag indicates that the next frame in the receive buffer had a parity error when received. if parity che ck is not enabled the upen bi t will always be read zero. for compatibility with future devices, always set this bit to zero when writing to ucsrna. for more details see ?parity bit calculation? on page 153 and ?parity checker? on page 160 . 18.7.5 parity checker the parity checker is active when the high usart parity mode (upmn1) bit is set. type of par- ity check to be performed (odd or even) is selected by the upmn0 bit. when enabled, the parity checker calculates the parity of the data bits in incoming frames and co mpares the result with the parity bit from the serial frame. the result of the check is stored in the receive buffer together with the received data and stop bits. the parity error (upen) flag can then be read by software to check if the frame had a parity error.
161 7799d?avr?11/10 atmega8u2/16u2/32u2 the upen bit is set if the next character that can be read from the receive buffer had a parity error when received and the parity checking was enabled at that point (upmn1 = 1). this bit is valid until the receive buffer (udrn) is read. 18.7.6 disabling the receiver in contrast to the transmitter, disabling of the receiver will be immediate. data from ongoing receptions will therefore be lost. when disabled (i.e., the rxenn is set to zero) the receiver will no longer override the normal function of the rxdn port pin. the receiver buffer fifo will be flushed when the receiver is disabled. remaining data in the buffer will be lost 18.7.7 flushing the receive buffer the receiver buffer fifo will be flushed when the receiver is disabled, i.e., the buffer will be emptied of its contents. unread data will be lost. if the buffer has to be flushed during normal operation, due to for instance an error condition, read the udrn i/o location until the rxcn flag is cleared. the following code example shows how to flush the receive buffer. note: 1. see ?code examples? on page 6. 18.8 asynchronous data reception the usart includes a clock recovery and a data recovery unit for handling asynchronous data reception. the clock recovery logic is used for synchronizing the internally generated baud rate clock to the incoming asynchronous serial frames at the rxdn pin. the data recovery logic sam- ples and low pass filters each incoming bit, thereby improving the noise immunity of the receiver. the asynchronous reception operational range depends on the accuracy of the inter- nal baud rate clock, the rate of the incoming frames, and the frame size in number of bits. 18.8.1 asynchronous clock recovery the clock recovery logic synchronizes internal clock to the incoming serial frames. figure 18-5 illustrates the sampling process of the start bit of an incoming frame. the sample rate is 16 times the baud rate for normal mode, and eight times the baud rate for double speed mode. the hor- izontal arrows illustrate the synchronization variation due to the sampling process. note the larger time variation when using the double speed mode (u2xn = 1) of operation. samples denoted zero are samples done when the rxdn line is idle (i.e., no communication activity). assembly code example (1) usart_flush: sbis ucsrna, rxcn ret in r16, udrn rjmp usart_flush c code example (1) void usart_flush( void ) { unsigned char dummy; while ( ucsrna & (1< 162 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 18-5. start bit sampling when the clock recovery logic detects a high (idle) to low (start) transition on the rxdn line, the start bit detection sequence is initiated. let sa mple 1 denote the first zero-sample as shown in the figure. the clock recovery logic then uses samples 8, 9, and 10 for normal mode, and sam- ples 4, 5, and 6 for double speed mode (indicated with sample numbers inside boxes on the figure), to decide if a valid start bit is received. if two or more of these three samples have logical high levels (the majority wins), the start bit is rejected as a noise spike and the receiver starts looking for the next high to low-transition. if however, a valid start bit is detected, the clock recov- ery logic is synchronized and the data recovery can begin. the synchronization process is repeated for each start bit. 18.8.2 asynchronous data recovery when the receiver clock is synchronized to the start bit, the data recovery can begin. the data recovery unit uses a state machine that has 16 states for each bit in normal mode and eight states for each bit in double speed mode. figure 18-6 shows the sampling of the data bits and the parity bit. each of the samples is given a number that is equal to the state of the recovery unit. figure 18-6. sampling of data and parity bit the decision of the logic level of the received bit is taken by doing a majority voting of the logic value to the three samples in the center of the received bit. the center samples are emphasized on the figure by having the sample number inside boxes. the majority voting process is done as follows: if two or all three samples have high levels, the received bit is registered to be a logic 1. if two or all three samples have low levels, the received bit is registered to be a logic 0. this majority voting process acts as a low pass filter for the incoming signal on the rxdn pin. the recovery process is then repeated until a complete frame is received. including the first stop bit. note that the receiver only uses the first stop bit of a frame. figure 18-7 shows the sampling of the stop bit and the earliest possible beginning of the start bit of the next frame. 1234567 8 9 10 11 12 13 14 15 16 12 start idle 0 0 bit 0 3 123 4 5 678 12 0 rxd sample (u2x = 0) sample (u2x = 1) 1234567 8 9 10 11 12 13 14 15 16 1 bit n 123 4 5 678 1 rxd sample (u2x = 0) sample (u2x = 1)
163 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 18-7. stop bit sampling and next start bit sampling the same majority voting is done to the stop bit as done for the other bits in the frame. if the stop bit is registered to have a logic 0 value, the frame error (fen) flag will be set. a new high to low transition indicating the start bit of a new frame can come right after the last of the bits used for majority voting. for normal speed mode, the first low level sample can be at point marked (a) in figure 18-7 . for double speed mode the first low level must be delayed to (b). (c) marks a stop bit of full length. the early start bit detection influences the operational range of the receiver. 18.8.3 asynchronous operational range the operational range of the receiver is depen dent on the mismatch betw een the received bit rate and the internally generated baud rate. if the transmitter is sending frames at too fast or too slow bit rates, or the internally generated baud rate of the receiver does not have a similar (see table 18-2 ) base frequency, the receiver will not be able to synchronize the frames to the start bit. the following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate. d sum of character size and parity size (d = 5 to 10 bit) s samples per bit. s = 16 for normal speed mode and s = 8 for double speed mode. s f first sample number used for majority voting. s f = 8 for normal speed and s f = 4 for double speed mode. s m middle sample number used for majority voting. s m = 9 for normal speed and s m = 5 for double speed mode. r slow is the ratio of the slowest incoming data rate that can be accepted in relation to the receiver baud rate. r fast is the ratio of the fastest incoming data rate that can be accepted in relation to the receiver baud rate. table 18-2 and table 18-3 list the maximum receiver baud rate error that can be tolerated. note that normal speed mode has higher toleration of baud rate variations. 1234567 8 9 10 0/1 0/1 0/1 stop 1 123 4 5 6 0/1 rxd sample (u2x = 0) sample (u2x = 1) (a) (b) (c) r slow d 1 + ?? s s 1 ? ds ? s f ++ -------------------------------------------- = r fast d 2 + ?? s d 1 + ?? ss m + ------------------------------------ - =
164 7799d?avr?11/10 atmega8u2/16u2/32u2 the recommendations of the maximum receiver ba ud rate error was m ade under the assump- tion that the receiver and transmitter equally divides the maximum total error. there are two possible sources fo r the receivers baud rate erro r. the receiver?s system clock (xtal) will always have some minor instability over the supply voltage range and the tempera- ture range. when using a crystal to generate the system clock, this is rarely a problem, but for a resonator the system clock may differ more than 2% depending of the resonators tolerance. the second source for the error is more controllable. the baud rate generator can not always do an exact division of the system frequency to get the baud rate wanted. in this case an ubrr value that gives an acceptable low error can be used if possible. 18.9 multi-processor communication mode setting the multi-processor communication mode (mpcmn) bit in ucsrna enables a filtering function of incoming frames received by the usart receiver. frames that do not contain address information will be ignored and not put into the receive buffer. this effectively reduces the number of incoming frames that has to be handled by the cpu, in a system with multiple mcus that communicate via the same serial bus. the transmitter is unaffected by the mpcmn setting, but has to be used differently when it is a part of a system utiliz ing the multi-processor communication mode. if the receiver is set up to receive frames that contain 5 to 8 data bits, then the first stop bit indi- cates if the frame contains data or address information. if the receiver is set up for frames with nine data bits, then the ninth bit (rxb8n) is used for identifying address and data frames. when the frame type bit (the first stop or the ninth bit) is one, the frame contains an address. when the frame type bit is zero the frame is a data frame. table 18-2. recommended maximum receiver baud rate error for normal speed mode (u2xn = 0) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 93.20 106.67 +6.67/-6.8 3.0 6 94.12 105.79 +5.79/-5.88 2.5 7 94.81 105.11 +5.11/-5.19 2.0 8 95.36 104.58 +4.58/-4.54 2.0 9 95.81 104.14 +4.14/-4.19 1.5 10 96.17 103.78 +3.78/-3.83 1.5 table 18-3. recommended maximum receiver baud rate error for double speed mode (u2xn = 1) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 94.12 105.66 +5.66/-5.88 2.5 6 94.92 104.92 +4.92/-5.08 2.0 7 95.52 104,35 +4.35/-4.48 1.5 8 96.00 103.90 +3.90/-4.00 1.5 9 96.39 103.53 +3.53/-3.61 1.5 10 96.70 103.23 +3.23/-3.30 1.0
165 7799d?avr?11/10 atmega8u2/16u2/32u2 the multi-processor communication mode enables several slave mcus to receive data from a master mcu. this is done by first decoding an address frame to find out which mcu has been addressed. if a particular slave mcu has been addressed, it will receive the following data frames as normal, while the other slave mcus will ignore the received frames until another address frame is received. 18.9.1 using mpcmn for an mcu to act as a master mcu, it can use a 9-bit character frame format (ucszn = 7). the ninth bit (txb8n) must be set when an address frame (txb8n = 1) or cleared when a data frame (txb = 0) is being transmitted. the slave mcus must in this case be set to use a 9-bit character frame format. the following procedure should be used to exchange data in multi-processor communication mode: 1. all slave mcus are in multi-processor communication mode (mpcmn in ucsrna is set). 2. the master mcu sends an address frame, and all slaves receive and read this frame. in the slave mcus, the rxcn flag in ucsrna will be set as normal. 3. each slave mcu reads the udrn register and determines if it has been selected. if so, it clears the mpcmn bit in ucsrna, otherwise it waits for the next address byte and keeps the mpcmn setting. 4. the addressed mcu will receive all data frames until a new address frame is received. the other slave mcus, which still have the mpcmn bit set, will ignore the data frames. 5. when the last data frame is received by the addressed mcu, the addressed mcu sets the mpcmn bit and waits for a new address frame from master. the process then repeats from 2. using any of the 5- to 8-bit character frame formats is possible, but impractical since the receiver must change between using n and n+1 character frame formats. this makes full- duplex operation difficult since the transmitter and receiver uses the same character size set- ting. if 5- to 8-bit character frames are used, the transmitter must be set to use two stop bit (usbsn = 1) since the first stop bit is used for indicating the frame type. do not use read-modify-write instructions (sbi and cbi) to set or clear the mpcmn bit. the mpcmn bit shares the same i/o location as the txcn flag and this might accidentally be cleared when using sbi or cbi instructions. 18.10 hardware flow control the hardware flow control can be enabled by software. cts : (clear to send) r ts : (request to send) 18.10.1 receiver flow control the reception flow can be controlled by hardware using the r ts pin. the aim of the flow control is to inform the external transmitter when the internal receive fifo is full. thus the transmitter can txd atmega8u2/16u rts txd rxd host rxd cts cts r ts
166 7799d?avr?11/10 atmega8u2/16u2/32u2 stop sending characters. r ts usage and so associated flow control is enabled using rtsen bit in ucsrnd. figure 18-8. shows a reception example. figure 18-8. reception flow control waveform example figure 18-9. rts behavior rts will rise at 2/3 of the last received stop bit if the receive fifo is full. to ensure reliable transmissions, even after a r t s rise, an extra-data can still be received and stored in the receive shift register. 18.10.2 transmission flow control the transmission flow can be controlled by hardware using the cts pin controlled by the exter- nal receiver. the aim of the flow control is to stop transmission when the receiver is full of data ( c t s = 1). c t s usage and so associated flow control is enabled using ctsen bit in ucsrnd. the c t s pin is sampled at each cpu write and at the middle of the last stop bit that is curently being sent. figure 18-10. cts behavior r ts rxd c1 c2 0 1 2 fifo 1 cpu read index c3 1 0 r ts rxd start byte0 stop start byte1 stop read from cpu start byte2 1 additional byte may be sent if the transmitter misses the rts trig cts txd start byte0 stop start byte1 stop start byte2 sample sample w rite from cpu sample
167 7799d?avr?11/10 atmega8u2/16u2/32u2 18.11 register description 18.11.1 udrn ? usart i/o data register n the usart transmit data buffer register and usart receive data buffer registers share the same i/o address referred to as usart data register or udrn. the transmit data buffer reg- ister (txb) will be the destination for data written to the udrn register location. reading the udrn register location will return the contents of the receive data buffer register (rxb). for 5-, 6-, or 7-bit characters the upper unused bits will be ignored by the transmitter and set to zero by the receiver. the transmit buffer can only be written when the udren flag in the ucsrna register is set. data written to udrn when the udren flag is not set, will be ignored by the usart transmit- ter. when data is written to the transmit buffer , and the transmitter is enabled, the transmitter will load the data into the transmit shift register when the shift register is empty. then the data will be serially transmitted on the txdn pin. the receive buffer consists of a two level fifo. the fifo will change its state whenever the receive buffer is accessed. due to this behavior of the receive buffer, do not use read-modify- write instructions (sbi and cbi) on this location. be careful when using bit test instructions (sbic and sbis), since these also will change the state of the fifo. 18.11.2 ucsrna ? usart control and status register a ? bit 7 ? rxcn: usart receive complete this flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). if the receiver is disabled, the receive buffer will be flushed and consequently the rxcn bit will become zero. the rxcn flag can be used to generate a receive complete interrupt (see description of the rxcien bit). ? bit 6 ? txcn: usart transmit complete this flag bit is set when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer (udrn). the txcn flag bit is auto- matically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txcn flag can generate a transmit complete interrupt (see description of the txcien bit). ? bit 5 ? udren: usart data register empty the udren flag indicates if the transmit buffer (udrn) is ready to receive new data. if udren is one, the buffer is empty, and therefore ready to be written. the udren flag can generate a data register empty interrupt (see description of the udrien bit). udren is set after a reset to indicate that the transmitter is ready. bit 76543210 rxb[7:0] udrn (read) txb[7:0] udrn (write) read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 rxcn txcn udren fen dorn upen u2xn mpcmn ucsrna read/write r r/w r r r r r/w r/w initial value 00100000
168 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 4 ? fen: frame error this bit is set if the next character in the rece ive buffer had a frame error when received. i.e., when the first stop bit of the next character in the receive buffer is zero. this bit is valid until the receive buffer (udrn) is read. the fen bit is zero when the stop bit of received data is one. always set this bit to zero when writing to ucsrna. ? bit 3 ? dorn: data overrun this bit is set if a data overrun condition is detected. a data overrun occurs when the receive buffer is full (two characters), it is a new character waiting in the receive shift register, and a new start bit is detected. this bit is valid until the receive buffer (udrn) is read. always set this bit to zero when writing to ucsrna. ? bit 2 ? upen: usart parity error this bit is set if the next character in the receive buffer had a parity error when received and the parity checking was enabled at that point (upmn1 = 1). this bit is valid until the receive buffer (udrn) is read. always set this bit to zero when writing to ucsrna. ? bit 1 ? u2xn: double the usart transmission speed this bit only has effect for the asynchronous operation. write this bit to zero when using syn- chronous operation. writing this bit to one will reduce the divisor of the baud rate divider from 16 to 8 effectively dou- bling the transfer rate for asynchronous communication. ? bit 0 ? mpcmn: multi-processor communication mode this bit enables the multi-processor communication mode. when the mpcmn bit is written to one, all the incoming frames received by the usart receiver that do not contain address infor- mation will be ignored. the transmitter is unaffected by the mpcmn setting. for more detailed information see ?multi-processor communication mode? on page 164 . 18.11.3 ucsrnb ? usart control and status register n b ? bit 7 ? rxcien: rx complete interrupt enable n writing this bit to one enables interrupt on the rxcn flag. a usart receive complete interrupt will be generated only if the rxcien bit is written to one, the global interrupt flag in sreg is written to one and the rxcn bit in ucsrna is set. ? bit 6 ? txcien: tx complete interrupt enable n writing this bit to one enables interrupt on the txcn flag. a usart transmit complete interrupt will be generated only if the txcien bit is written to one, the global interrupt flag in sreg is written to one and the txcn bit in ucsrna is set. ? bit 5 ? udrien: usart data register empty interrupt enable n writing this bit to one enables interrupt on the udren flag. a data register empty interrupt will be generated only if the udrien bit is written to one, the global interrupt flag in sreg is written to one and the udren bit in ucsrna is set. bit 76543210 rxcien txcien udrien rxenn txenn ucszn2 rxb8n txb8n ucsrnb read/write r/w r/w r/w r/w r/w r/w r r/w initial value 0 0 0 0 0 0 0 0
169 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 4 ? rxenn: receiver enable n writing this bit to one enables the usart receiver. the receiver will override normal port oper- ation for the rxdn pin when enabled. disabling the receiver will flush the receive buffer invalidating the fen, dorn, and upen flags. ? bit 3 ? txenn: transmitter enable n writing this bit to one enables the usart transmitter. the transmitter will override normal port operation for the txdn pin when enabled. the disabling of the transmitter (writing txenn to zero) will not become effective until ongoing and pending transmissions are completed, i.e., when the transmit shift register and transmit buffer register do not contain data to be trans- mitted. when disabled, the transmitter will no longer override the txdn port. ? bit 2 ? ucszn2: character size n the ucszn2 bits combined with the ucszn1:0 bit in ucsrnc sets the number of data bits (character size) in a frame the receiver and transmitter use. ? bit 1 ? rxb8n: receive data bit 8 n rxb8n is the ninth data bit of the received character when operating with serial frames with nine data bits. must be read before reading the low bits from udrn. ? bit 0 ? txb8n: transmit data bit 8 n txb8n is the ninth data bit in the character to be transmitted when operating with serial frames with nine data bits. must be written before writing the low bits to udrn. 18.11.4 ucsrnc ? usart control and status register n c ? bits 7:6 ? umseln[1:0] usart mode select these bits select the mode of operation of the usartn as shown in table 18-4 .. note: 1. see ?usart in spi mode? on page 176 for full description of the master spi mode (mspim) operation ? bits 5:4 ? upmn1:0: parity mode these bits enable and set type of parity generation and check. if enabled, the transmitter will automatically generate and send the parity of the transmitted data bits within each frame. the bit 7 6 5 4 3 2 1 0 umseln1 umseln0 upmn1 upmn0 usbsn ucszn1 ucszn0 ucpoln ucsrnc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 1 1 0 table 18-4. umseln bits settings umseln1 umseln0 mode 0 0 asynchronous usart 0 1 synchronous usart 1 0 (reserved) 1 1 master spi (mspim) (1)
170 7799d?avr?11/10 atmega8u2/16u2/32u2 receiver will generate a parity value for the incoming data and compare it to the upmn setting. if a mismatch is detected, the upen flag in ucsrna will be set. ? bit 3 ? usbsn: stop bit select this bit selects the number of stop bits to be inserted by the transmitter. the receiver ignores this setting. ? bit 2:1 ? ucszn1:0: character size the ucszn1:0 bits combined with the ucszn2 bit in ucsrnb sets the number of data bits (character size) in a frame the receiver and transmitter use. ? bit 0 ? ucpoln: clock polarity this bit is used for synchronous mode only. write this bit to zero when asynchronous mode is used. the ucpoln bit sets the relationship between data output change and data input sample, and the synchronous clock (xckn). table 18-5. upmn bits settings upmn1 upmn0 parity mode 0 0 disabled 0 1 reserved 1 0 enabled, even parity 1 1 enabled, odd parity table 18-6. usbs bit settings usbsn stop bit(s) 0 1-bit 1 2-bit table 18-7. ucszn bits settings ucszn2 ucszn1 ucszn0 character size 0 0 0 5-bit 0 0 1 6-bit 0 1 0 7-bit 0 1 1 8-bit 1 0 0 reserved 1 0 1 reserved 1 1 0 reserved 1 1 1 9-bit table 18-8. ucpoln bit settings ucpoln transmitted data changed (output of txdn pin) received data sampled (input on rxdn pin) 0 rising xckn edge falling xckn edge 1 falling xckn edge rising xckn edge
171 7799d?avr?11/10 atmega8u2/16u2/32u2 18.11.5 ucsrnd ? usart control and status register n d ? bits 1 ? ctsen : usart cts enable set this bit to one by firmware to enable the transmission flow control (cts). transmission is allowed if cts = 0. set this bit to zero by firmware to disable the transmission flow control (cts). transmission is always allowed. ? bits 0 ? rtsen : usart rts enable set this bit to one by firmware to enable the receive flow control (rts). set this bit to zero by firmware to disable the receive flow control (rts). 18.11.6 ubrrnl and ubrrnh ? usart baud rate registers ? bit 15:12 ? reserved bits these bits are reserved for future use. for compatibility with future devices, these bit must be written to zero when ubrrh is written. ? bit 11:0 ? ubrr[11:0]: usart baud rate register this is a 12-bit register which contains the usart baud rate. the ubrrh contains the four most significant bits, and the ubrrl contains the eight least significant bits of the usart baud rate. ongoing transmissions by the transmitter and receiver will be corrupted if the baud rate is changed. writing ubrrl will trigger an immediate update of the baud rate prescaler. 18.12 examples of baud rate setting for standard crystal and resonator frequencies, the most commonly used baud rates for asyn- chronous operation can be generated by using the ubrr settings in table 18-9 to table 18-12 . ubrr values which yield an actual baud rate differing less than 0.5% from the target baud rate, are bold in the table. higher error ratings are a cceptable, but the receiver will have less noise resistance when the error ratings are high, especially for large serial frames (see ?asynchronous operational range? on page 163 ). the error values are calculated using the following equation: bit 7 6 5 4 3 2 1 0 - - - - - - ctsen rtsen ucsrnd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 15 14 13 12 11 10 9 8 ? ? ? ? ubrr[11:8] ubrrnh ubrr[7:0] ubrrnl 76543210 read/write r r r r r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 00000000 error[%] baudrate closest match baudrate -------------------------------------------------------- 1 ? ?? ?? 100% ? =
172 7799d?avr?11/10 atmega8u2/16u2/32u2 table 18-9. examples of ubrrn settings for commonly used oscillator frequencies baud rate (bps) f osc = 1.0000 mhz f osc = 1.8432 mhz f osc = 2.0000 mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 25 0.2% 51 0.2% 47 0.0% 95 0.0% 51 0.2% 103 0.2% 4800 12 0.2% 25 0.2% 23 0.0% 47 0.0% 25 0.2% 51 0.2% 9600 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 12 0.2% 25 0.2% 14.4k 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 19.2k 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 28.8k 1 8.5% 3 8.5% 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 38.4k 1 -18.6% 2 8.5% 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 57.6k 0 8.5% 1 8.5% 1 0.0% 3 0.0% 1 8.5% 3 8.5% 76.8k ? ? 1 -18.6% 1 -25.0% 2 0.0% 1 -18.6% 2 8.5% 115.2k ? ? 0 8.5% 0 0.0% 1 0.0% 0 8.5% 1 8.5% 230.4k ??????0 0.0% ? ? ? ? 250k ??????????0 0.0% max. (1) 62.5 kbps 125 kbps 115.2 kbps 230.4 kbps 125 kbps 250 kbps 1. ubrr = 0, error = 0.0%
173 7799d?avr?11/10 atmega8u2/16u2/32u2 table 18-10. examples of ubrrn settings for commonly used oscillator frequencies (continued) baud rate (bps) f osc = 3.6864 mhz f osc = 4.0000 mhz f osc = 7.3728 mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 95 0.0% 191 0.0% 103 0.2% 207 0.2% 191 0.0% 383 0.0% 4800 47 0.0% 95 0.0% 51 0.2% 103 0.2% 95 0.0% 191 0.0% 9600 23 0.0% 47 0.0% 25 0.2% 51 0.2% 47 0.0% 95 0.0% 14.4k 15 0.0% 31 0.0% 16 2.1% 34 -0.8% 31 0.0% 63 0.0% 19.2k 11 0.0% 23 0.0% 12 0.2% 25 0.2% 23 0.0% 47 0.0% 28.8k 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 15 0.0% 31 0.0% 38.4k 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 57.6k 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 76.8k 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 115.2k 1 0.0% 3 0.0% 1 8.5% 3 8.5% 3 0.0% 7 0.0% 230.4k 0 0.0% 1 0.0% 0 8.5% 1 8.5% 1 0.0% 3 0.0% 250k 0 -7.8% 1 -7.8% 0 0.0% 1 0.0% 1 -7.8% 3 -7.8% 0.5m ? ? 0 -7.8% ? ? 0 0.0% 0 -7.8% 1 -7.8% 1m ??????????0 -7.8% max. (1) 230.4 kbps 460.8 kbps 250 kbps 0.5 mbps 460.8 kbps 921.6 kbps 1. ubrr = 0, error = 0.0%
174 7799d?avr?11/10 atmega8u2/16u2/32u2 table 18-11. examples of ubrrn settings for commonly used oscillator frequencies (continued) baud rate (bps) f osc = 8.0000 mhz f osc = 11.0592 mhz f osc = 14.7456 mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 207 0.2% 416 -0.1% 287 0.0% 575 0.0% 383 0.0% 767 0.0% 4800 103 0.2% 207 0.2% 143 0.0% 287 0.0% 191 0.0% 383 0.0% 9600 51 0.2% 103 0.2% 71 0.0% 143 0.0% 95 0.0% 191 0.0% 14.4k 34 -0.8% 68 0.6% 47 0.0% 95 0.0% 63 0.0% 127 0.0% 19.2k 25 0.2% 51 0.2% 35 0.0% 71 0.0% 47 0.0% 95 0.0% 28.8k 16 2.1% 34 -0.8% 23 0.0% 47 0.0% 31 0.0% 63 0.0% 38.4k 12 0.2% 25 0.2% 17 0.0% 35 0.0% 23 0.0% 47 0.0% 57.6k 8 -3.5% 16 2.1% 11 0.0% 23 0.0% 15 0.0% 31 0.0% 76.8k 6 -7.0% 12 0.2% 8 0.0% 17 0.0% 11 0.0% 23 0.0% 115.2k 3 8.5% 8 -3.5% 5 0.0% 11 0.0% 7 0.0% 15 0.0% 230.4k 1 8.5% 3 8.5% 2 0.0% 5 0.0% 3 0.0% 7 0.0% 250k 1 0.0% 3 0.0% 2 -7.8% 5 -7.8% 3 -7.8% 6 5.3% 0.5m 0 0.0% 1 0.0% ? ? 2 -7.8% 1 -7.8% 3 -7.8% 1m ? ? 0 0.0% ? ???0 -7.8% 1 -7.8% max. (1) 0.5 mbps 1 mbps 691.2 kbps 1.3824 mbps 921.6 kbps 1.8432 mbps 1. ubrr = 0, error = 0.0%
175 7799d?avr?11/10 atmega8u2/16u2/32u2 table 18-12. examples of ubrrn settings for commonly used oscillator frequencies (continued) baud rate (bps) f osc = 16.0000 mhz f osc = 18.4320 mhz f osc = 20.0000 mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 416 -0.1% 832 0.0% 479 0.0% 959 0.0% 520 0.0% 1041 0.0% 4800 207 0.2% 416 -0.1% 239 0.0% 479 0.0% 259 0.2% 520 0.0% 9600 103 0.2% 207 0.2% 119 0.0% 239 0.0% 129 0.2% 259 0.2% 14.4k 68 0.6% 138 -0.1% 79 0.0% 159 0.0% 86 -0.2% 173 -0.2% 19.2k 51 0.2% 103 0.2% 59 0.0% 119 0.0% 64 0.2% 129 0.2% 28.8k 34 -0.8% 68 0.6% 39 0.0% 79 0.0% 42 0.9% 86 -0.2% 38.4k 25 0.2% 51 0.2% 29 0.0% 59 0.0% 32 -1.4% 64 0.2% 57.6k 16 2.1% 34 -0.8% 19 0.0% 39 0.0% 21 -1.4% 42 0.9% 76.8k 12 0.2% 25 0.2% 14 0.0% 29 0.0% 15 1.7% 32 -1.4% 115.2k 8 -3.5% 16 2.1% 9 0.0% 19 0.0% 10 -1.4% 21 -1.4% 230.4k 3 8.5% 8 -3.5% 4 0.0% 9 0.0% 4 8.5% 10 -1.4% 250k 3 0.0% 7 0.0% 4 -7.8% 8 2.4% 4 0.0% 9 0.0% 0.5m 1 0.0% 3 0.0% ? ? 4 -7.8% ? ? 4 0.0% 1m 0 0.0% 1 0.0% ? ??????? max. (1) 1 mbps 2 mbps 1.152 mbps 2.304 mbps 1.25 mbps 2.5 mbps 1. ubrr = 0, error = 0.0%
176 7799d?avr?11/10 atmega8u2/16u2/32u2 19. usart in spi mode 19.1 features ? full duplex, three-wire synchronous data transfer ? master operation ? supports all four spi modes of operation (mode 0, 1, 2, and 3) ? lsb first or msb first data transfer (configurable data order) ? queued operation (double buffered) ? high resolution baud rate generator ? high speed operation (fxckmax = fck/2) ? flexible interrupt generation 19.2 overview the universal synchronous and asynchronous serial receiver and transmitter (usart) can be set to a master spi compliant mode of operat ion. setting both umseln1:0 bits to one enables the usart in mspim logic. in th is mode of operation the spi ma ster control logic takes direct control over the usart resources. these resources include the transmitter and receiver shift register and buffers, and the baud rate generator. the parity generator and checker, the data and clock recovery logic, and the rx and tx control logic is disabled. the usart rx and tx control logic is replaced by a common spi transfe r control logic. however, the pin control logic and interrupt generation logic is identical in both modes of operation. the i/o register locations are the same in both modes. however, some of the functionality of the control registers changes when using mspim. 19.3 clock generation the clock generation logic generates the base clock for the transmitter and receiver. for usart mspim mode of operation only internal clock generation (i.e. master operation) is sup- ported. the data direction register for the xckn pin (ddr_xckn) must therefore be set to one (i.e. as output) for the usart in mspim to operate correctly. preferably the ddr_xckn should be set up before the usart in mspim is enabled (i.e. txenn and rxenn bit set to one). the internal clock generation used in mspim mode is identical to the usart synchronous mas- ter mode. the baud rate or ubrrn setting can therefore be calculated using the same equations, see table 19-1 :
177 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. the baud rate is defined to be the transfer rate in bit per second (bps) baud baud rate (in bits per second, bps) f osc system oscillator clock frequency ubrrn contents of the ubrrnh and ubrrnl registers, (0-4095) 19.4 spi data modes and timing there are four combinations of xckn (sck) phase and polarity with respect to serial data, which are determined by control bits ucphan and ucpoln. the data transfer timing diagrams are shown in figure 19-1 . data bits are shifted out and latched in on opposite edges of the xckn signal, ensuring sufficient time for data signals to stabilize. the ucpoln and ucphan function- ality is summarized in table 19-2 . note that changing the setting of any of these bits will corrupt all ongoing communication for both the receiver and transmitter. figure 19-1. ucphan and ucpoln data transfer timing diagrams. table 19-1. equations for calculating baud rate register setting operating mode equation for calculating baud rate (1) equation for calculating ubrrn value synchronous master mode baud f osc 2 ubrr n 1 + ?? -------------------------------------- - = ubrr n f osc 2 baud -------------------- 1 ? = table 19-2. ucpoln and ucphan functionality- ucpoln ucphan spi mode leading edge trailing edge 0 0 0 sample (rising) setup (falling) 0 1 1 setup (rising) sample (falling) 1 0 2 sample (falling) setup (rising) 1 1 3 setup (falling) sample (rising) xck data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd) ucpol=0 ucpol=1 ucpha=0 ucpha=1
178 7799d?avr?11/10 atmega8u2/16u2/32u2 19.5 frame formats a serial frame for the mspim is defined to be one character of 8 data bits. the usart in mspim mode has two valid frame formats: ? 8-bit data with msb first ? 8-bit data with lsb first a frame starts with the least or most significant data bit. then the next data bits, up to a total of eight, are succeeding, ending with the most or least significant bit accordingly. when a complete frame is transmitted, a new frame can directly follow it, or the communication line can be set to an idle (high) state. the udordn bit in ucsrnc sets the frame fo rmat used by the usart in mspim mode. the receiver and transmitter use the same setting. not e that changing the setting of any of these bits will corrupt all ongoing communication for both the receiver and transmitter. 16-bit data transfer can be achieved by writing two data bytes to udrn. a uart transmit com- plete interrupt will then signal that the 16-bit value has been shifted out. 19.5.1 usart mspim initialization the usart in mspim mode has to be initialized before any communication can take place. the initialization process normally consists of setting the baud rate, setting master mode of operation (by setting ddr_xckn to one), setting frame format and enabling the transmitter and the receiver. only the transmitter can operate independently. for interrupt driven usart opera- tion, the global interrupt flag should be cleared (and thus interrupts globally disabled) when doing the initialization. note: to ensure immediate initialization of the xckn output the baud-rate register (ubrrn) must be zero at the time the transmitter is enabled. contrary to the normal mode usart operation the ubrrn must then be written to the desired value after the transmitter is enabled, but before the first transmission is started. setting ubrrn to zero before enabling the transmitter is not neces- sary if the initialization is done immediately after a reset since ubrrn is reset to zero. before doing a re-initialization with changed baud rate, data mode, or frame format, be sure that there is no ongoing transmissions during the per iod the registers are changed. the txcn flag can be used to check that the transmitter has co mpleted all transfers, and the rxcn flag can be used to check that there are no unread data in the receive buffer. note that the txcn flag must be cleared before each transmission (before udrn is written) if it is used for this purpose. the following simple usart initialization code examples show one assembly and one c func- tion that are equal in functionality. the examples assume polling (no interrupts enabled). the baud rate is given as a function parameter. fo r the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers.
179 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. see ?code examples? on page 6. 19.6 data transfer using the usart in mspi mode requires the transmitter to be enabled, i.e. the txenn bit in the ucsrnb register is set to one. when the transmitter is enabled, the normal port operation of the txdn pin is overridden and given the function as the transmitter's serial output. enabling the receiver is optional and is done by setting the rxenn bit in the ucsrnb register to one. when the receiver is enabled, the normal pin operation of the rxdn pin is overridden and given the function as the receiver's serial input. the xckn will in both cases be used as the transfer clock. after initialization the usart is ready for doing data transfers. a data transfer is initiated by writ- ing to the udrn i/o location. this is the case for both sending and receiving data since the assembly code example (1) usart_init: clr r18 out ubrrnh,r18 out ubrrnl,r18 ; setting the xckn port pin as output, enables master mode. sbi xckn_ddr, xckn ; set mspi mode of operation and spi data mode 0. ldi r18, (1< 180 7799d?avr?11/10 atmega8u2/16u2/32u2 transmitter controls the transfer clock. the data written to udrn is moved from the transmit buf- fer to the shift register when the shift register is ready to send a new frame. note: to keep the input buffer in sync with the number of data bytes transmitted, the udrn register must be read once for each byte transmitted. the input buffer operation is identical to normal usart mode, i.e. if an overflow occurs the character last received will be lost, not the first data in the buf- fer. this means that if four bytes are transferred, byte 1 first, then byte 2, 3, and 4, and the udrn is not read before all transfers are completed, then byte 3 to be received will be lost, and not byte 1. the following code examples show a simple usart in mspim mode transfer function based on polling of the data register empty (udren) flag and the receive complete (rxcn) flag. the usart has to be initialized before the function can be used. for the assembly code, the data to be sent is assumed to be stored in register r16 and the data received will be available in the same register (r16) after the function returns. the function simply waits for the transmit buffer to be empty by checking the udren flag, before loading it with new data to be transmitted. the function then waits for data to be present in the receive buffer by checking the rxcn flag, before reading the buffer and returning the value.. note: 1. see ?code examples? on page 6. assembly code example (1) usart_mspim_transfer: ; wait for empty transmit buffer sbis ucsrna, udren rjmp usart_mspim_transfer ; put data (r16) into buffer, sends the data out udrn,r16 ; wait for data to be received usart_mspim_wait_rxcn: sbis ucsrna, rxcn rjmp usart_mspim_wait_rxcn ; get and return received data from buffer in r16, udrn ret c code example (1) unsigned char usart_receive( void ) { /* wait for empty transmit buffer */ while ( !( ucsrna & (1< 181 7799d?avr?11/10 atmega8u2/16u2/32u2 19.6.1 transmitter and receiver flags and interrupts the rxcn, txcn, and udren flags and corresponding interrupts in usart in mspim mode are identical in function to the normal usart operation. however, the receiver error status flags (fe, dor, and pe) are not in use and is always read as zero. 19.6.2 disabling the transmitter or receiver the disabling of the transmitter or receiver in usart in mspim mode is identical in function to the normal usart operation. 19.7 register description the following section describes the registers used for spi operation using the usart. 19.7.1 udrn ? usart mspim i/o data register the function and bit description of the usart data register (udrn) in mspi mode is identical to normal usart operation. see ?udrn ? usart i/o data register n? on page 167. 19.7.2 ucsrna ? usart mspim control and status register n a ? ? bit 7 - rxcn: usart receive complete this flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). if the receiver is disabled, the receive buffer will be flushed and consequently the rxcn bit will become zero. the rxcn flag can be used to generate a receive complete interrupt (see description of the rxcien bit). ? bit 6 - txcn: usart transmit complete this flag bit is set when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer (udrn). the txcn flag bit is auto- matically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txcn flag can generate a transmit complete interrupt (see description of the txcien bit). ? bit 5 - udren: usart data register empty the udren flag indicates if the transmit buffer (udrn) is ready to receive new data. if udren is one, the buffer is empty, and therefore ready to be written. the udren flag can generate a data register empty interrupt (see description of the udrie bit). udren is set after a reset to indicate that the transmitter is ready. ? bit 4:0 - reserved bits in mspi mode when in mspi mode, these bits are reserved for future use. for compatibility with future devices, these bits must be written to zero when ucsrna is written. bit 7 6 5 4 3 2 1 0 rxcn txcn udren - - - - - ucsrna read/write r/w r/w r/w r r r r r initial value 0 0 0 0 0 1 1 0
182 7799d?avr?11/10 atmega8u2/16u2/32u2 19.7.3 ucsrnb ? usart mspim control and status register n b ? bit 7 - rxcien: rx complete interrupt enable writing this bit to one enables interrupt on the rxcn flag. a usart receive complete interrupt will be generated only if the rxcien bit is written to one, the global interrupt flag in sreg is written to one and the rxcn bit in ucsrna is set. ? bit 6 - txcien: tx complete interrupt enable writing this bit to one enables interrupt on the txcn flag. a usart transmit complete interrupt will be generated only if the txcien bit is written to one, the global interrupt flag in sreg is written to one and the txcn bit in ucsrna is set. ? bit 5 - udrie: usart data register empty interrupt enable writing this bit to one enables interrupt on the udren flag. a data register empty interrupt will be generated only if the udrie bit is written to one, the global interrupt flag in sreg is written to one and the udren bit in ucsrna is set. ? bit 4 - rxenn: receiver enable writing this bit to one enables the usart receiver in mspim mode. the receiver will override normal port operation for the rxdn pin when enabled. disabling the receiver will flush the receive buffer. only enabling the receiver in mspi mode (i.e. setting rxenn=1 and txenn=0) has no meaning since it is the transmitter that controls the transfer clock and since only master mode is supported. ? bit 3 - txenn: transmitter enable writing this bit to one enables the usart transmitter. the transmitter will override normal port operation for the txdn pin when enabled. the disabling of the transmitter (writing txenn to zero) will not become effective until ongoing and pending transmissions are completed, i.e., when the transmit shift register and transmit buffer register do not contain data to be trans- mitted. when disabled, the transmitter will no longer override the txdn port. ? bit 2:0 - reserved bits in mspi mode when in mspi mode, these bits are reserved for future use. for compatibility with future devices, these bits must be written to zero when ucsrnb is written. bit 7 6 5 4 3 2 1 0 rxcien txcien udrie rxenn txenn ? ? ? ucsrnb read/write r/w r/w r/w r/w r/w r r r initial value 0 0 0 0 0 1 1 0
183 7799d?avr?11/10 atmega8u2/16u2/32u2 19.7.4 ucsrnc ? usart mspim control and status register n c ? bit 7:6 - umseln[1:0]: usart mode select these bits select the mode of operation of the usart as shown in table 19-3 . see ?ucsrnc ? usart control and status register n c? on page 169 for full description of the normal usart operation. the mspim is enabled when both umseln bits are set to one. the udordn, ucphan, and ucpoln can be set in the same write operation where the mspim is enabled. ? bit 5:3 - reserved bits in mspi mode when in mspi mode, these bits are reserved for future use. for compatibility with future devices, these bits must be written to zero when ucsrnc is written. ? bit 2 - udordn: data order when set to one the lsb of the data word is transmitted first. when set to zero the msb of the data word is transmitted first. refer to the frame formats section page 4 for details. ? bit 1 - ucphan: clock phase the ucphan bit setting determine if data is sample d on the leasing edge (first) or tailing (last) edge of xckn. refer to the spi data modes and timing section page 4 for details. ? bit 0 - ucpoln: clock polarity the ucpoln bit sets the polarity of the xckn clock. the combination of the ucpoln and ucphan bit settings determine the timing of the data transfer. refer to the spi data modes and timing section page 4 for details. 19.7.5 ubrrnl and ubrrnh ? usart mspim baud rate registers the function and bit description of the baud rate registers in mspi mode is identical to normal usart operation. see ?ubrrnl and ubrrnh ? usart baud rate registers? on page 171. 19.8 avr usart mspim vs. avr spi the usart in mspim mode is fully compatible with the avr spi regarding: ? master mode timing diagram. ? the ucpoln bit functionality is identical to the spi cpol bit. ? the ucphan bit functionality is identical to the spi cpha bit. ? the udordn bit functionality is identical to the spi dord bit. bit 7 6 5 4 3 2 1 0 umseln1 umseln0 ? ? ? udordn ucphan ucpoln ucsrnc read/write r/w r/w r r r r/w r/w r/w initial value 0 0 0 0 0 1 1 0 table 19-3. umseln bits settings umseln1 umseln0 mode 0 0 asynchronous usart 0 1 synchronous usart 1 0 (reserved) 1 1 master spi (mspim)
184 7799d?avr?11/10 atmega8u2/16u2/32u2 however, since the usart in mspim mode reuses the usart resources, the use of the usart in mspim mode is somewhat different compared to the spi. in addition to differences of the control register bits, and that only master operation is supported by the usart in mspim mode, the following features differ between the two modules: ? the usart in mspim mode includes (double) buffering of the transmitter. the spi has no buffer. ? the usart in mspim mode receiver includes an additional buffer level. ? the spi wcol (write collision) bit is not included in usart in mspim mode. ? the spi double speed mode (spi2x) bit is not included. however, the same effect is achieved by setting ubrrn accordingly. ? interrupt timing is not compatible. ? pin control differs due to the master only operation of the usart in mspim mode. a comparison of the usart in mspim mode and the spi pins is shown in table 19-4 on page 184 . table 19-4. comparison of usart in mspim mode and spi pins. usart_mspim spi comment txdn mosi master out only rxdn miso master in only xckn sck (functionally identical) (n/a) ss not supported by usart in mspim
185 7799d?avr?11/10 atmega8u2/16u2/32u2 20. usb controller 20.1 features ? usb 2.0 full-speed device ? ping-pong mode (dual bank), with transparent switch ? 176 bytes of dpram ? 1 endpoint of 64 bytes max (default control endpoint) ? 2 endpoints of 64 bytes max (one bank) ? 2 endpoints of 64 bytes max (one or two banks) 20.2 overview the usb controller provides the hardware to implement a usb2.0 compliant full-speed usb device in the atmega8u2/16u2/32u2. a simplified block diagram of the usb controller is shown in figure 20-1 on page 185 . the usb controller requires a 48 mhz 0.25% reference clock for usb full-speed compliance. this clock is generated by an internal pll. the reference clock to the pll must be provided from an external crystal or an external clock input. only thes e two clock options will be able to provide a reference clock within the accuracy and jitter requirements of the usb specification. see section ?system clock and clock options? on page 26 for details on the atmega8u2/16u2/32u2 system clock and clock options. to comply to the usb specifications electrical characteristics, the usb pads (d+ or d-) must be powered at 3.0v to 3.6v. as the atmega8u2/16u2/32u2 can be powered up to 5.5v, an inter- nal regulator is provided to correctly power the usb pads. see ?usb module powering options? on page 186 for details on the powering options available for the usb controller figure 20-1. usb controller block diagram cpu reg u l a tor u s b interf a ce pll 6x clk 8 mhz clk 4 8 mhz pll clock pre s c a ler on-chip u s b dpram dpll clock recovery ucap d- d+ uvcc xtal1
186 7799d?avr?11/10 atmega8u2/16u2/32u2 20.3 usb module powering options depending on the selected target application power supply (v cc ), the atmega8u2/16u2/32u2 usb controller requires different powering schemes, see figure 20-2 on page 186 . figure 20-2. operating modes versus frequency and power-supply 20.3.1 bus powered device the following figures show typical implementations for different powering schemes. figure 20-3. typical bus powered application with 5v i/o vcc (v) vcc min 0 3 .0 4.0 5.5 u s b not operational u s b compliant, without internal regulator u s b compliant, with internal regulator 4.5 2.7 max operating frequency (mhz) 8 mhz 16 mhz 2 mhz 3 .6 1f udm udp vbus uvss ucap d- d+ uvcc vcc avcc uv ss v ss xtal1 xtal2
187 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 20-4. typical bus powered application with 3.3v i/o 20.3.2 self powered device figure 20-5. typical self powered application with 4.0v to 5.5v i/o. 1f udm udp vbus uvss ucap d- d+ uvcc vcc uv ss v ss xtal1 xtal2 avcc 1f external 3 .4v - 5.5v power s upply udp udm vbu s uv ss uid ucap d- d+ vbu s uid ugnd uvcc avcc vcc xtal1 xtal2 gnd gnd r s =22 r s =22
188 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 20-6. typical self powered application with 3.0v to 3.6 i/o (1) note: 1. the internal 3.3v regulator is bypassed. disable the regulator to avoid additional power con- sumption. see the ?regcr ? regulator control register? on page 196 for details. 1f external 3 .0v - 3 .6v power s upply udp udm vbus uvss uid ucap d- d+ vbu s uid ugnd uvcc avcc vcc xtal1 xtal2 gnd gnd rs=22 rs=22
189 7799d?avr?11/10 atmega8u2/16u2/32u2 20.3.3 design guidelines the following design guidelines should be met: ? serial resistors on usb data lines must have 22 ohms value ( +/- 5%). ? traces from the input usb receptacle (or from the cable connection in the case of a tethered device) to the usb microcontroller pads should be as short as possible, and follow differential traces routing rules (same length, as near as possible and avoid vias accumulation). ? voltage transient / esd suppressors may also be used to prevent usb pads to be damaged by external disturbances. ?u cap capacitor should be 1 f ( +/- 10%) for correct operation. in addition it is highly recommended to connect a 10 f capacitor to the vbus line 20.4 general operating modes 20.4.1 introduction the usb controller is disabled and reset after a hardware reset generated by: ? power on reset ? external reset ? watchdog reset ? brown out reset ? debugwire reset ? usb end of reset in the case of usb end of reset (eor), the usb controller is reset, but not disabled. therefore the device remains attached. 20.4.2 power-on and reset figure 20-7 on page 189 illustrates the usb controller main states on power-on: figure 20-7. usb controller states after reset re s et device any other s t a te u s be = 0 u s be = 0 u s be = 1 hw re s et (except from eor) u s be = 0 hw re s et (from eor) clock s topped frzclk = 1 (m a cro off)
190 7799d?avr?11/10 atmega8u2/16u2/32u2 when the usb controller is in reset state: ? usbe is not set ? the usb controller clock is stopped in order to minimize the power consumption (frzclk=1) ? the usb controller is disabled ? usb is in the suspend mode ? the device usb controllers internal state is reset ? the dpacc bit and the dpadd10:0 field can be set by software. the dpram is not cleared. ? the spdconf bits can be set by software after setting usbe, the usb controller enters in the device state. the usb controller can at any time be reset by clearing usbe. 20.4.3 interrupts two interrupts vectors are assigned to the usb controller. figure 20-8. usb interrupt system the usb module distinguishes between usb general events and usb endpoints events. figure 20-9. usb general interrupt vector sources the wakeup interrupt allows device wake-up from power-down mode, and is an asynchronous interrupt, triggering each time a state change is detected on the data lines. the other interrupts are synchronous and will be detected only if the usb clock is enabled (frzclk bit set). usb device interrupt usb general interrupt vector endpoint interrupt usb endpoint/pipe interrupt vector uprsmi udint.6 uprsme udien.6 eorsmi udint.5 eorsme udien.5 wakeupi udint.4 wakeupe udien.4 eorsti udint.3 eorste udien.3 sofi udint.2 sofe udien.2 suspi udint.0 suspe udien.0 usb general interrupt vector asynchronous interrupt source (allows the cpu to wake up from power down mode)
191 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 20-10. usb endpoint interrupt vector sources each endpoint has 8 interrupts sources associated with flags, and each source can be enabled to trigger the corresponding endpoint interrupt. if, for an endpoint, at least one of the sources is enabled to trigger interrupt, the corresponding event(s) will make the program branch to the usb endpoint interrupt vector. the user may determine the source (endpoint) of the interrupt by reading the ?udint ? usb device interrupt register? on page 210 . 20.5 power modes 20.5.1 idle mode in idle mode, the cpu is halted (cpu clock stopped). the idle mode is taken wether the usb controller is running or not. the cpu can wake up on any usb interrupts. 20.5.2 power-down in power-down mode, the oscillator is stopped and halts all the clocks (cpu and peripherals). the usb controller wakes up when: ? the wakeupi interrupt is triggered (single asynchronous interrupt) flerre ueienx.7 overfi uestax.6 underfi uestax.5 nakini ueintx.6 nakine ueienx.6 nakouti ueintx.4 txstpe ueienx.4 rxstpi ueintx.3 txoute ueienx.3 rxouti ueintx.2 rxoute ueienx.2 stalledi ueintx.1 stallede ueienx.1 epint ueint.x endpoint 0 endpoint 1 endpoint 2 endpoint 3 endpoint 4 txini ueintx.0 txine ueienx.0 usb endpoi interrupt ve c
192 7799d?avr?11/10 atmega8u2/16u2/32u2 20.5.3 freeze clock the firmware has the ability to freeze the clock of usb controller by setting the frzclk bit, and thereby reduce the power consumption. when frzclk is set, it is still possible to access to the following registers: ? usbcon ? dpram direct access registers (dpadd7:0, uedatx) ? udcon ? udint ? udien when frzclk is set, only the asynchronous interrupt may be triggered: ? wakeupi 20.6 memory management the controller does only support the following memory allocation management. the reservation of an endpoint can only be made in the increasing order (endpoint 0 to the last endpoint). the firmware shall thus configure them in the same order. the reservation of an endpoint k i is done when its alloc bit is set. then, the hardware allo- cates the memory and insert it between the endpoints k i-1 and k i+1 . the k i+1 endpoint memory ?slides? up and its data is lost. note that the k i+2 and upper endpoint memory does not slide. clearing an endpoint enable (epen) does not clear either its alloc bit, or its configuration (epsize/psize, epbk/pbk). to free its memory, the firmware should clear alloc. then, the k i+1 endpoint memory automatically slides down. note that the k i+2 and upper endpoint memory does not slide. the following figure illustrates the allocation and reorganization of the usb memory in a typical example: table 20-1. allocation and reorganization usb memory flow
193 7799d?avr?11/10 atmega8u2/16u2/32u2 ? endpoints activation: endpoint 0 to endpoint 4 are configured, in the growing order. the memory of each is reserved in the dpram. ? endpoint disable: the endpoint 2 is disabled (epen=0), but its memory reservation is internally kept by the controller. ? free its memory: the alloc bit is cleared: the endpoint 3 slides down, but the endpoint 4 does not slide. ? endpoint activation: the firmware chooses to reconfigure the endpoint 2, but with a bigger size. the controller reserved the memory after the endpoint 1 memory and automatically slide the endpoint 3. the endpoint 4 does not move and a memory conflict appear, in that both endpoint 3 and 4 use a common area. the data of those endpoints are potentially lost. note that: ? the data of endpoint 0 is never lost at activation or deactivation of a higher endpoint. the data is lost only if the endpoint 0 is deactivated. ? deactivate and reactivate the same endpoint with the same parameters does not lead to a slide of the higher endpoints. for those endpoints, the data are preserved. ? cfgok is set by hardware even in the case that there is a ?conflict? in the memory allocation. 20.7 pad suspend the next figures illustrates the pad behaviour: ? in the idle mode, the pad is put in low power consumption mode. ? in the active mode, the pad is working. figure 20-11. pad behaviour the suspi flag indicated that a suspend state has been detected on the usb bus. this flag automatically put the usb pad in idle. the detection of a non-idle event sets the wakeupi flag and wakes-up the usb pad.
194 7799d?avr?11/10 atmega8u2/16u2/32u2 moreover, the pad can also be put in the idle mode if the detach bit is set. it come back in the active mode when the detach bit is cleared. 20.8 d+/d- read/write the level of d+ and d- can be read and written using the upoe register. the usb controller has to be enabled to write a value. for read operation, the usb controller can be enabled or disabled. 20.9 usb software operating modes depending on the usb operating mode, the software should perform some of the following operations: power on the usb interface ? configure pll interface ? enable pll ? check pll lock ? enable usb interface ? configure usb interface (usb endpoint 0 configuration) ? attach usb device power off the usb interface ? detach usb device ? disable usb interface ? disable pll suspending the usb interface ? clear suspend bit ? set usb suspend clock ? disable pll suspi suspend detected = usb pad power down clear suspend by software resume = usb pad wake-up clear resume by software wakeupi pad status active power down active
195 7799d?avr?11/10 atmega8u2/16u2/32u2 ? be sure to have interrupts enabled (wakeupe) to exit sleep mode ? put the mcu in sleep mode resuming the usb interface ? enable pll ? wait pll lock ? clear usb suspend clock ? clear resume information 20.10 registers description 20.10.1 usbcon ? usb general control registers ? bit 7 ? usbe: usb macro enable bit writing this bit to one enables the usb controller and the usb data buffers (d+ and d-). clear- ing this bit disables the usb controller and buffers. when cleared the usb controller is reset. ? bit 6 ? res: reserved this bit is reserved and should always read as zero. ? bit 5 ? frzclk: freeze usb clock bit writing this bit to one disables the internal cloc k for the usb controller, and tehreby freezing it. activating this mode reduces power consumption. all the usb flags are kept unchanged. only the ?resume detection? is still active in this mode. writing this bit to zero unfreezes the usb controller and allows full operation of the usb interface. ? bits 4:0 ? res: reserved these bits are reserved and should always read as zero. 20.10.2 upoe ? usb software output enable register ? bit 7:6 ? upwe[1:0]: usb buffers direct drive enable configuration these bits select the mode of operation of the usb buffers according to table 20-2 . the possi- ble configurations of these bits allows to enable or disable the usb buffers direct drive by soft- ware. when direct drive for usb buffers is enable, the updrv[1:0] values are output to the bit 76543210 (0xd8) usbe - frzlk - - - - - usbcon read/write r/w r r/w r r r r r initial value 0 0 1 0 0 0 0 0 bit 7 6 5 4 3 2 1 0 (0xfb) upwe1 upwe0 updrv1 updrv0 - - dpi dmi upoe read/write r/w r/w r/w r/w rrrr initial value 0 0 0 0 0 0 0 0
196 7799d?avr?11/10 atmega8u2/16u2/32u2 buffers. ? bit 5:4 ? updrv[1:0]: usb direct drive values these bits are relevant only when one of the direct drive modes for usb is enable. when upwe[1:0] is 1:0 the values of these bits are output to usb. the value written to updrv1 is output to d+. the value written to updrv0 is output to d-. ? bits 3:2 ? res: reserved these bits are reserved and should always read as zero. ? bit 1 ? dpi: d+ input value this bit is read only, the value read from this bit reflects the d+ pin (usb buffer). this bit is set one by hardware if a one logic level is read on d+. this bit is set to zero by hardware if a zero logic level is read on d+. ? bit 0 ? dmi: d- input value this bit is read only, the value read from this bit reflects the d- pin (usb buffer). this bit is set one by hardware if a logic one is read on d-. this bit is set to zero by hardware if a logic zero logic is read on d-. 20.10.3 regcr ? regulator control register ? bit 0 ? regdis: regulator disable writing this bit to a logic one disables the internal 3.3v regulator. writing this bit to a logic zero enables the regulstor. table 20-2. upwe[i:0] bits settings upwe1 upwe0 mode 00 direct drive is disabled. 01 reserved 10 direct drive of dp/dm (updrv[1:0] values) 11 reserved bit 76543210 (0x63) - - - - - - - regdis regcr read/write r r r r r r r r/w initial value 0 0 0 0 0 0 0 0
197 7799d?avr?11/10 atmega8u2/16u2/32u2 21. usb device operating modes 21.1 overview the usb device controller supports full speed data transfers. in addition to the default control endpoint, it provides four other endpoints, which ca n be configured in control, bulk, interrupt or isochronous modes: the controller starts in the ?idle? mode. in this mode, the pad consumption is reduced to the minimum. 21.2 power-on and reset the next diagram explains the usb device controller main states on power-on: figure 21-1. usb device controller states after reset the reset state of the device controller is: ? the macro clock is stopped in order to minimize the power consumption (frzclk set), ? the usb device controller internal state is reset (all the registers are reset to their default value. note that detach is set.) ? the endpoint banks are reset ? the d+ pull up are not activated (mode detach) the d+ pull-up will be activated as soon as the detach bit is cleared. the macro is in the ?idle? state after reset with a minimum power consumption and does not need to have the pll activated to enter in this state. the usb device controller can at any time be reset by clearing usbe. 21.3 endpoint reset an endpoint can be reset at any time by setting in the uerst register the bit corresponding to the endpoint (eprstx). this resets: ? the internal state machine on that endpoint, ? endpoint 0: programmable size fifo up to 64 bytes, default control endpoint ? endpoint 1 and 2: programmable size fifo up to 64 bytes. ? endpoint 3 and 4: programmable size fifo up to 64 bytes with ping-pong mode.
198 7799d?avr?11/10 atmega8u2/16u2/32u2 ? the rx and tx banks are cleared and their internal pointers are restored, ? the ueintx, uesta0x and uesta1x are restored to their reset value. the data toggle field remains unchanged. the other registers remain unchanged. the endpoint configuration remains active and the endpoint is still enabled. the endpoint reset may be associated with a clear of the data toggle command (rstdt bit) as an answer to the clear_feature usb command. 21.4 usb reset when an usb reset is detected on the usb line (seo state with a minimal duration of 100 s), the next operations are performed by the controller: ? all the endpoints are disabled. ? the default control endpoint remains configured. ? the data toggle of the default control endpoint is cleared. if the hardware reset function is selected, a reset is generated to the cpu core without disabling the usb controller (that remains in the same state than after a usb reset). 21.5 endpoint selection prior to any operation performed by the cpu, the endpoint must first be selected. this is done by setting the epnum[2:0] bits (in uenum register) with the endpoint number which will be managed by the cpu. the cpu can then access to the various endpoint registers and data. 21.6 endpoint activation the endpoint is maintained under reset as long as the epen bit is not set. the following flow must be respected in order to activate an endpoint:
199 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 21-2. endpoint activation flow: as long as the endpoint is not correctly configured (cfgok cleared), the hardware does not acknowledge the packets sent by the host. cfgok will not be set if the endpoint size parameter is bigger than the dpram size. a clear of epen acts as an endpoint reset (see ?endpoint reset? on page 197 for more details). it also performs the next operation: ? the configuration of the endpoint is kept (epsize, epbk, alloc kept) ? it resets the data toggle field. ? the dpram memory associated to the endpoint is still reserved. see ?memory management? on page 192 for more details about the memory allocation/reorganization. 21.7 address setup the usb device address is set up according to the usb protocol: ? the usb device, after power-up, responds at address 0 ? the host sends a setup command (set_address(addr)), ? the firmware records that address in uadd, but keep adden cleared, ? the usb device sends an in command of 0 bytes (in 0 zero length packet) to acknowledge the transaction, ? then, the firmware may enable the usb device address by setting adden. the only accepted address by the controller is the one stored in uadd. adden and uadd shall not be written at the same time.
200 7799d?avr?11/10 atmega8u2/16u2/32u2 uadd contains the default address 00h after a power-up or an usb reset. adden is cleared by hardware: ? after a power-up reset, ? when an usb reset is received, ? or when the macro is disabled (usbe cleared) when this bit is cleared, the default device address 00h is used. 21.8 suspend, wake-up and resume after the usb line has been inactive for a period of 3 ms (j state), the controller set the suspi flag and triggers the corresponding interrupt if enabled. the firmware may then set the frzclk bit. the cpu can also, depending on software architecture, disable the pll and/or enter in the idle mode to reduce the power consumption (especially in a bus powered application). there are two ways to recover from the suspend mode: 1. clear the frzclk bit. this is possible if the cpu is not in the idle mode. 2. if the cpu is in idle mode, enable the wakeupi interrupt (wakeupe set). then, as soon as an non-idle signal is seen by the controller, the wakeupi interrupt is triggered. the firmware shall then clear the frzclk bit to restart the transfer. there are no relationship between the suspi interrupt and the wakeupi interrupt: the wake- upi interrupt is triggered as soon as there are non-idle patterns on the data lines. thus, the wakeupi interrupt can occurs even if the controller is not in the ?suspend? mode. when the wakeupi interrupt is triggered, if the suspi interrupt bit was already set, it is cleared by hardware. when the suspi interrupt is triggered, if the wakeupi interrupt bit was already set, it is cleared by hardware. 21.9 detach the reset value of the detach bit is 1. it is possible to re-enumerate a device, simply by setting and clearing the detach bit (the line discharge time must be taken in account). ? when the usb device controller is in full-speed mode, setting detach will disconnect the pull-up on the d+. then, clearing detach will connect the pull-up on the d+. figure 21-3. detach a device in full-speed:
201 7799d?avr?11/10 atmega8u2/16u2/32u2 21.10 remote wake-up the remote wake-up (or upstream resume) request is the only operation allowed to be sent by the device on its own initiative. anyway, to do that, the device should first have received a device_remote_wakeup request from the host. ? first, the usb controller must have detected the ?suspend? state of the line: the remote wake-up can only be sent if the suspi bit is set. ? the firmware has then the ability to set rmwkup to send the ?upstream resume? stream. this will automatically be done by the controller after 5ms of inactivity on the usb line. ? when the controller starts to send the ?upstream resume?, the uprsmi flag is set and interrupt is triggered (if enabled). if suspi was set, suspi is cleared by hardware. ? rmwkup is automatically cleared by hardware at the end of the ?upstream resume?. ? after that, if the controller detects a good ?end of resume? signal from the host, an eorsmi interrupt is triggered (if enabled). 21.11 stall request for each endpoint, the stall management is performed using 2 bits: ? stallrq (enable stall request) ? stallrqc (disable stall request) ? stalledi (stall sent interrupt) to send a stall handshake at the next request, the stallrq request bit has to be set. all fol- lowing requests will be handshak?ed with a stall until the stallrqc bit is set. setting stallrqc automatically clears the stal lrq bit. the stallrqc bit is also immedi- ately cleared by hardware after being set by software. thus, the firmware will never read this bit as set. each time the stall handshake is sent, the stalledi flag is set by the usb controller and the epintx interrupt will be triggered (if enabled). the incoming packets will be discarded (rxouti and rwal will not be set). the host will then send a command to reset the stall: the firmware just has to set the stall- rqc bit and to reset the endpoint. 21.11.1 special consideration for control endpoints a setup request is always ack?ed. if a stall request is set for a control endpoint and if a setup request occurs, the setup request has to be ack?ed and the stallrq request and stalledi sent flags are automati- cally reset (rxsetupi set, txin cleared, stalled cleared, txini cleared...). this management simplifies the enumeration process management. if a command is not sup- ported or contains an error, the firmware set the stall request flag and can return to the main task, waiting for the next setup request. this function is compliant with the chapter 8 test that sends extra status for a get_descriptor. the firmware sets the stall request just after receiving the status. all extra status will be automatically stall?ed until the next setup request.
202 7799d?avr?11/10 atmega8u2/16u2/32u2 21.11.2 stall handshake and retry mechanism the retry mechanism has priority over the stall handshake. a stall handshake is sent if the stallrq request bit is set and if there is no retry required. 21.12 control endpoint management a setup request is always ack?ed. when a new setup packet is received, the rxstpi inter- rupt is triggered (if enabled). the rxouti interrupt is not triggered. the fifocon and rwal fields are irrelevant with control endpoints. the firmware shall thus never use them on that endpoints. when read, their value is always 0. control endpoints are managed by the following bits: ? rxstpi is set when a new setup is received. it shall be cleared by firmware to acknowledge the packet and to clear the endpoint bank . ? rxouti is set when a new out data is received. it shall be cleared by firmware to acknowledge the packet and to clear the endpoint bank . ? txini is set when the bank is ready to accept a new in packet. it shall be cleared by firmware to send the packet and to clear the endpoint bank . control endpoints should not be managed by interrupts, but only by polling the status bits. 21.12.1 control write the next figure shows a control write transaction. during the status stage, the controller will not necessary send a nak at the first in token: ? if the firmware knows the exact number of descriptor bytes that must be read, it can then anticipate on the status stage and send a zlp for the next in token, ? or it can read the bytes and poll nakini, which tells that all the bytes have been sent by the host, and the transaction is now in the status stage.
203 7799d?avr?11/10 atmega8u2/16u2/32u2 21.12.2 control read the next figure shows a control read transaction. the usb controller has to manage the simulta- neous write requests from the cpu and the usb host: a nak handshake is always generated at the first status stage command. when the controller detect the status stage, all the data written by the cpu are erased, and clearing txini has no effects. the firmware checks if the transmission is complete or if the reception is complete. the out retry is always ack'ed. this reception: - set the rxouti flag (received out data) - set the txini flag (data sent, ready to accept new data) software algorithm: set transmit ready wait (transmit complete or receive complete) if receive complete, clear flag and return if transmit complete, continue once the out status stage has been received, the usb controller waits for a setup request. the setup request have priority over any other request and has to be ack?ed. this means that any other flag should be cleared and the fifo reset when a setup is received. warning: the byte counter is reset when a out zero length packet is received. the firmware has to take care of this. 21.13 out endpoint management out packets are sent by the host. all the data can be read by the cpu, which acknowledges or not the bank when it is empty. 21.13.1 overview the endpoint must be configured first.
204 7799d?avr?11/10 atmega8u2/16u2/32u2 21.13.1.1 ?manual? mode each time the current bank is full, the rxouti and the fifocon bits are set. this triggers an interrupt if the rxoute bit is set. the firmware can acknowledge the usb interrupt by clearing the rxouti bit. the firmware read the data and clear the fifocon bit in order to free the cur- rent bank. if the out endpoint is composed of multiple banks, clearing the fifocon bit will switch to the next bank. the rxouti and fifocon bits are then updated by hardware in accordance with the status of the new bank. rxouti shall always be cleared before clearing fifocon. the rwal bit always reflects the state of the current bank. this bit is set if the firmware can read data from the bank, and cleared by hardware when the bank is empty. 21.13.2 detailed description the data are read by the cpu, following the next flow: ? when the bank is filled by the host, an endpoint interrupt (epintx) is triggered, if enabled (rxoute set) and rxouti is set. the cpu can also poll rxouti or fifocon, depending on the software architecture, ? the cpu acknowledges the interrupt by clearing rxouti, ? the cpu can read the number of byte (n) in the current bank (n=byct), ? the cpu can read the data from the current bank (?n? read of uedatx),
205 7799d?avr?11/10 atmega8u2/16u2/32u2 ? the cpu can free the bank by clearing fifocon when all the data is read, that is: ? after ?n? read of uedatx, ? as soon as rwal is cleared by hardware. if the endpoint uses 2 banks, the second one can be filled by the host while the current one is being read by the cpu. then, when the cpu clear fifocon, the next bank may be already ready and rxouti is set immediately. 21.14 in endpoint management in packets are sent by the usb device controller, upon an in request from the host. all the data can be written by the cpu, which acknowledge or not the bank when it is full. 21.14.1 overview the endpoint must be configured first. 21.14.1.1 ?manual? mode the txini bit is set by hardware when the current bank becomes free. this triggers an interrupt if the txine bit is set. the fifocon bit is set at the same time. the cpu writes into the fifo and clears the fifocon bit to allow the usb controller to send the data. if the in endpoint is composed of multiple banks, this also switches to the next data bank. the txini and fifocon bits are automatically updated by hardware regarding the status of the next bank. txini shall always be cleared before clearing fifocon.
206 7799d?avr?11/10 atmega8u2/16u2/32u2 the rwal bit always reflects the state of the current bank. this bit is set if the firmware can write data to the bank, and cleared by hardware when the bank is full. 21.14.2 detailed description the data are written by the cpu, following the next flow: ? when the bank is empty, an endpoint interrupt (epintx) is triggered, if enabled (txine set) and txini is set. the cpu can also poll txini or fifocon, depending the software architecture choice, ? the cpu acknowledges the interrupt by clearing txini, ? the cpu can write the data into the current bank (write in uedatx), ? the cpu can free the bank by clearing fifocon when all the data are written, that is: ? after ?n? write into uedatx ? as soon as rwal is cleared by hardware. if the endpoint uses 2 banks, the second one can be read by the host while the current is being written by the cpu. then, when the cpu clears fifocon, the next bank may be already ready (free) and txini is set immediately. 21.14.2.1 abort an ?abort? stage can be produced by the host in some situations:
207 7799d?avr?11/10 atmega8u2/16u2/32u2 ? in a control transaction: zlp data out received during a in stage, ? in an isochronous in transaction: zlp data out received on the out endpoint during a in stage on the in endpoint the killbk bit is used to kill the last ?written? bank. the best way to manage this abort is to per- form the following operations: table 21-1. abort flow 21.15 isochronous mode 21.15.1 underflow an underflow can occur during in stage if the host attempts to read a bank which is empty. in this situation, the underfi interrupt is triggered. an underflow can also occur during out stage if the host send a packet while the banks are already full. typically, he cpu is not fast enough. the packet is lost. it is not possible to have underflow error during out stage, in the cpu side, since the cpu should read only if the bank is ready to give data (rxouti=1 or rwal=1) 21.15.2 crc error a crc error can occur during out stage if the usb controller detects a bad received packet. in this situation, the stalledi interrupt is trigge red. this does not prevent the rxouti interrupt from being triggered. 21.16 overflow in control, isochronous, bulk or interrupt endpoint, an overflow can occur during out stage, if the host attempts to write in a bank that is too small for the packet. in this situation, the overfi interrupt is triggered (if enabled). the packet is acknowledged and the rxouti interrupt is also triggered (if enabled). the bank is filled with the first bytes of the packet.
208 7799d?avr?11/10 atmega8u2/16u2/32u2 it is not possible to have overflow error during in stage, in the cpu side, since the cpu should write only if the bank is ready to access data (txini=1 or rwal=1). 21.17 interrupts the next figure shows all the interrupts sources: figure 21-4. usb device controller interrupt system there are 2 kind of interrupts: processing (i.e. their generation are part of the normal processing) and exception (errors). processing interrupts are generated when: ? upstream resume( uprsmi ) ? end of resume( eorsmi ) ? wake up( wakeupi ) ? end of reset (speed initialization)( eorsti ) ? start of frame( sofi , if fncerr=0) ? suspend detected after 3 ms of inactivity( suspi ) exception interrupts are generated when: ? crc error in frame number of sof( sofi , fncerr=1) uprsmi udint.6 uprsme udien.6 eorsmi udint.5 eorsme udien.5 wakeupi udint.4 wakeupe udien.4 eorsti udint.3 eorste udien.3 sofi udint.2 sofe udien.2 suspi udint.0 suspe udien.0 usb device interrupt
209 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 21-5. usb device controller endpoint interrupt system processing interrupts are generated when: ? ready to accept in data( epintx , txini=1) ? received out data( epintx , rxouti=1) ? received setup( epintx , rxstpi=1) exception interrupts are generated when: ? stalled packet( epintx , stalledi=1) ? crc error on out in isochronous mode( epintx , stalledi=1) ? overflow( epintx , overfi=1) ? underflow in isochronous mode( epintx , underfi=1) ? nak in sent( epintx , nakini=1) ? nak out sent( epintx , nakouti=1) 21.18 register description 21.18.1 udcon ? usb device control registers epint ueint.x endpoint 0 endpoint 1 endpoint 2 endpoint 3 endpoint 4 endpoint interrupt flerre ueienx.7 overfi uestax.6 underfi uestax.5 nakini ueintx.6 nakine ueienx.6 nakouti ueintx.4 txstpe ueienx.4 rxstpi ueintx.3 txoute ueienx.3 rxouti ueintx.2 rxoute ueienx.2 stalledi ueintx.1 stallede ueienx.1 txini ueintx.0 txine ueienx.0 bit 76543210 (0xe0) - - - - - rstcpu rmwkup detach udcon read/write r r r r r r/w r/w r/w initial value 0 0 000001
210 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bits 7:3 ? res: reserved these bits are reserved and will always read as zero. ? bit 2 ? rstcpu: usb reset cpu bit writing this bit to one allows the cpu controller to reset the cpu when a usb bus reset condi- tion is detected. when this mode is activated, the next usb bus reset event allows to reset the cpu and all peripherals except the usb controller. this mode allows to perform a software reset, but keep the usb device attached to the bus. this bit is reset when the usb controller is disabled or when writing this bit to zero by firmware. writing this bit to zero makes the cpu system reset independent from the usb bus reset event. ? bit 1 ? rmwkup: remote wake-up bit writing this bit to one allows the usb controller to generate an ?upstream-resume? packet on the usb bus. this bit is immediately cleared by hardware and can not be read back to one. writing this bit to zero has no effect. see ?remote wake-up? on page 201 for more details. ? bit 0 ? detach: detach bit writing this bit to one (default value) disables the usb d+ internal pull-up. this makes the usb device controller physically ?detached? from the usb bus. writing this bit to zero enables the d+ internal pull-up and physically connects the usb device controller to the usb bus. see ?detach? on page 200 for more details. 21.18.2 udint ? usb device interrupt register ? bit 7 ? res: reserved this bit is reserved and should always read as zero. ? bit 6 ? uprsmi: upstream resume interrupt flag this flag is set by hardware when the usb controller has successfully sent the upstream resume sequence (see description of ?bit 1 ? rmwkup: remote wake-up bit? on page 210 ). if uprsme is set, the uprsmi flag can generate a ?usb general interrupt?. writing this bit to zero acknowledges the interrupt source (usb clocks must be enabled before). writing this bit to one has no effect. ? bit 5 ? eorsmi: end of resume interrupt flag this flag is set by hardware when the usb c ontroller detects an end of resume sequence on the usb initiated by the host. if the eorsme bit is set, the eorsmi flag can generate a ?usb general interrupt?. writing this bit to zero acknowledges the interr upt source (usb clocks must be enabled before). writing this bit to one has no effect. bit 76543210 (0xe1) - uprsmi eorsmi wakeupi eorsti sofi - suspi udint read/write r r/w r/w r/w r/w r/w r r/w initial value 0 0 000000
211 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 4 ? wakeupi: wake-up cpu interrupt flag this flag is set by hardware when the usb controller detects a non-idle signal from the usb lines. this wakeupi flag can generate a ?usb general interrupt? if wakeupe bit is set. writing this bit to zero acknowledges the interrupt source. writing this bit to one has no effect.shall be cleared by software. setting by software has no effect. see ?suspend, wake-up and resume? on page 200 for more details. ? bit 3 ? eorsti: end of reset interrupt flag this flag is set by hardware when the usb controller detects an ?end of reset? event on the usb lines. has been detected by the usb controller. this eorsti flag can generate a ?usb general interrupt? if eorste bit is set. writing this bit to zero acknowledges the interrupt source (usb clocks must be enabled before). writing this bit to one has no effect. shall be cleared by software. setting by software has no effect. ? bit 2 ? sofi: start of frame interrupt flag this flag is set by hardware when the usb controller detects a start of frame pid (sof) on the usb lines. this sofi flag can generate a ?usb general interrupt? if sofe bit is set. writing this bit to zero acknowledges the interrupt source (usb clocks must be enabled before). writing this bit to one has no effect. ? bit 1 ? res: reserved this bit is reserved and will always read as zero. ? bit 0 ? suspi: suspend interrupt flag this flag is set by hardware when the usb controller detects a suspend state on the bus (idle state for more than 3ms). this suspi flag can generate a usb general interrupt if suspe bit is set. writing this bit to zero acknowledges the interrupt source (usb clocks must be enabled before). writing this bit to one has no effect. see ?suspend, wake-up and resume? on page 200 for more details. the interrupt flag bits are set even if their corresponding ?enable? bits is not set. 21.18.3 udien ? usb device interrupt enable register ? bit 7 ? res: reserved this bit is reserved and will always read as zero. ? bit 6 ? uprsme: upstream resume interrupt enable bit writing this bit to one enables int errupt on uprsmi flag. an ups tream resume interrupt will be generated only if the uprsme bit is set to one, th e global interrupt flag in sreg is written to one and the uprsmi bit is set. bit 76543210 (0xe2) - uprsme eorsme wakeupe eorste sofe - suspe udien read/write r r/w r/w r/w r/w r/w r r/w initial value 0 0 0 00000
212 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 5 ? eorsme: end of resume interrupt enable bit writing this bit to one enables interrupt on eorsmi flag. an end of resume upstream resume interrupt will be generated only if the eorsme bit is set to one, the global interrupt flag in sreg is written to one, and the eorsmi bit is set. ? bit 4 ? wakeupe: wake-up cpu interrupt enable bit writing this bit to one enables interrupt on wakeupi flag. a wake-up interrupt will be generated only if the wakeupe bit is set to one, the global interrupt flag in sreg is written to one, and the wakeupi bit is set. ? bit 3 ? eorste: end of reset interrupt enable bit writing this bit to one enables interrupt on eorsti flag. a usb reset interrupt will be generated only if the eorste bit is set to one, the global interrupt flag in sreg is written to one, and the eorsti bit is set. ? bit 2 ? sofe: start of frame interrupt enable bit writing this bit to one enables interrupt on sofi flag. a start of frame usb reset interrupt will be generated only if the sofe bit is set to one, the global interrupt flag in sreg is written to one, and the sofi bit is set. ? bit 1 ? res: reserved this bit is reserved and will always read as zero. ? bit 0 ? suspe: suspend interrupt enable bit writing this bit to one enables interrupt on suspi flag. a suspend interrupt will be generated only if the suspe bit is set to one, the global interrupt flag in sreg is written to one, and the suspi bit is set. 21.18.4 udaddr ? usb device address register ? bit 7 ? adden: address enable bit writing this bit to one will enable the uadd[6:0] field as device address for the usb controller. when this bit is set the usb device controller will be able to answer all requests on the usb that refer to the uadd[6:0] usb bus address. see ?address setup? on page 199 for more details. ? bits 6:0 ? uadd[6:0]: usb address bits these bits contain the usb device address, that the usb controller should answer on the usb bus. this address should be enabled writing one to the adden bit. bit 76543210 (0xe3) adden uadd[6:0] udaddr read/write r/w r rrrrrr initial value 0 0 000000
213 7799d?avr?11/10 atmega8u2/16u2/32u2 21.18.5 udfnumh ? usb device frame number high register ? bits 7:3 ? res: reserved these bits are reserved and will always read as zero. ? bits 2:0 ? fnum[10:8]: frame number upper flag these bits are read-only and updated by the hardware usb controller. these bits contains the 3 msb of the 11-bits frame number information. the content of these bits is updated with the last received sof packet. these bits are updated even if a corrupted sof has been received. when a corrupted sof number is detected, the fncerr bit of udmfn is set. 21.18.6 udfnuml ? usb device frame number low register ? bits 7:0 ? fnum: frame number lower flag these bits are read-only and updated by the hardware usb controller. these bits contains the 8 lsb of the 11-bits frame number information. the content of these bits is updated with the last received sof packet. these bits are updated even if a corrupted sof has been received. when a corrupted sof number is detected, the fncerr bit of udmfn is set. 21.18.7 udmfn ? usb device micro frame number ? bit 7:5 ? res: reserved these bits are reserved and will always read as zero. ? bit 4 ? fncerr: frame number crc error flag this bit is set by the usb controller when a corrupted frame number in start of frame packet is received. when an incorrect frame number is detected both sofi flag and this bit are set. ? bits 3:0 ? res: reserved these bits are reserved and will always read as zero. bit 76543210 (0xe5) ----- fnum[10:8] udfnumh read/write r r r rrrrr initial value 0 0 0 00000 bit 76543210 (0xe4) fnum[7:0] udfnuml read/write r r r rrrrr initial value 0 0 000000 bit 7 6 5 4 3 2 1 0 (0xe6) - - - fncerr - - - - udmfn read/write r r r r/w r r r r initial value 0 0 0 0 0 0 0 0
214 7799d?avr?11/10 atmega8u2/16u2/32u2 21.18.8 uenum ? usb endpoint number register ? bits 7:3 ? res: reserved these bits are reserved and will always read as zero. ? bits 2:0 ? epnum[2:0] endpoint number bits writing these bits allows to select the hardware endpoint number that can be accessed by the cpu interface. this register select the target endpoint number for ueconex, uecfg0x, uecfg1x, uesta0x, uesta1x, ueintx, ueienx, uedatx, uebclx registers. see ?end- point selection? on page 198 for more details. 21.18.9 uerst ? usb endpoint reset register ? bits 7:5 ? res: reserved these bits are reserved and will always read as zero. ? bits 4:0 ? eprst[4:0]: endpoint fifo reset bits writing this bit to one keeps the selected endpoint (uenum register value) under reset state. selected. writing this bit to zero completes the endpoint reset operation and makes the endpoint usable. see ?endpoint reset? on page 197 for more information. 21.18.10 ueconx ? usb endpoint control register ? bits 7:6 ? res: reserved these bits are reserved and will always read as zero. ? bit 5 ? stallrq: stall request handshake bit writing this bit to one allows the usb controller to generate a stall answer for the next setup transaction received. this bit is cleared by hardware when the stall handshake is sent or when a new setup token is receiv ed. writing this bit to zero has no effect. the stall hand- shake can be abort using stallrqc bit. see ?stall request? on page 201 for more details. bit 76543210 (0xe9) - - - - - epnum[2:0] uenum read/write r r r r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xea) - - - eprst d4 eprst d3 eprst d2 eprst d1 eprst d0 uerst read/write r r r r/w r/w r/w r/w r/w initial value 0 0 0 00000 bit 765 4 3210 (0xeb) - - stallrq stallrqc rstdt - - epen ueconx read/write r r r/w r/w r/w r r r/w initial value 0 0 0 0 0 0 0 0
215 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 4 ? stallrqc: stall request clear handshake bit writing this bit to one disables the pending stall handshake mechanism triggered by stallrq bit. this bit can not be write to zero, it is cleared by hardware immediately after the write to one operation. see ?stall request? on page 201 for more details. ? bit 3 ? rstdt: reset data toggle bit writing this bit to one allows to reset the data to ggle bit field for the sele cted endpoint. this bit can not be write to zero, it is cleared by hardware immediately after the write to one operation. ? bits 2:1 ? res: reserved these bits are reserved and will always read as zero. ? bit 0 ? epen: endpoint enable bit writing this bit to one enables the selected endpoint. when the endpoint is enabled it can be configured and used by the usb controller. endpoint 0 shall always be enabled after a hardware or usb reset and participate in the device configuration. writing this bit to zero disables the cur- rent endpoint. see ?endpoint activation? on page 198 for more details. 21.18.11 uecfg0x ? usb endpoint configuration 0 register ? bit 7:6 ? eptype[1:0]: endpoint type bits these bits configure the endpoint type for the selected endpoint as shown in table 21-2 . ? bits 5:1 ? res: reserved these bits are reserved and will always read as zero. ? bit 0 ? epdir: endpoint direction bit writing this bit to one configures the selected endpoint in the in direction. writing this bit to zero configure the endpoint in the out direction. this bit is relevant for bulk, interrupt or isochronous endpoints. using this bit with a control endpoint has no effect (control endpoints are bidirectional). bit 76543210 (0xec) eptype1:0 ----- epdir uecfg0x read/write r/w r/w r r r r r r/w initial value 0 0 000000 table 21-2. eptype[1:0] bits settings eptype1 eptype0 endpoint type configuration 00 control type 01 isochronous type 10 bulk type 11 interrupt type
216 7799d?avr?11/10 atmega8u2/16u2/32u2 21.18.12 uecfg1x ? usb endpoint configuration 1 register ? bit 7 ? res: reserved this bit is reserved and will always read as zero. ? bit 6:4 ? epsize[2:0]: endpoint size bits these bits configure the endpoint size for the selected endpoint as shown in table 21-3 . ? bits 3:2 ? epbk[1:0]: endpoint bank bits these bits configure the number of banks that is allocated to the selected endpoint as shown in table 21-3 . ? bit 1 ? alloc: endpoint allocation bit writing this to one allows to allocate the specified amount of memory (endpoint size x number of banks) for the selected endpoint. writing this bit to zero allows to free the previously allocated memory for the selected endpoint. see section 21.6, page 198 for more details. ? bit 0 ? res: reserved this bit is reserved and will always read as zero. bit 76543210 (0xed) - epsize[2:0] epbk1:0 alloc - uecfg1x read/write r r/w r/w r/w r/w r/w r/w r initial value 0 0 0 0 0 0 0 0 table 21-3. epsize[2:0] bits settings epsize2 epsize1 epsize0 endpoint size 000 8 bytes 001 16 bytes 010 32 bytes 011 64 bytes 100 reserved. 101 110 111 table 21-4. epbk[1:0] bits settings epbk1 epbk0 endpoint size 00 one bank 01 two banks 10 reserved 11
217 7799d?avr?11/10 atmega8u2/16u2/32u2 21.18.13 uesta0x ? usb endpoint status 0 register ? bit 7 ? cfgok: configuration status flag this flag bit is set by hardware when the selected endpoint size parameter (epsize) and num- ber of banks (epbk) are correct compared to the max fifo capacity. this bit is updated when the bit alloc is set, if the usb controller can not allocate the correct amount of memory for the selected endpoint, this flag bit will be cleared. if this bit is cleared, the user should reprogram the uecfg1x register with correct epsize and epbk values. ? bit 6 ? overfi: overflow error interrupt flag this flag is set when an overflow error occurs for an isochronous endpoint.this overfi flag can generate a ?usb endpoint interrupt? if flerre bit is set. writing this bit to zero acknowledges the interrupt source (usb clocks must be enabled before). writing this bit to one has no effect. see ?isochronous mode? on page 207 for more details. ? bit 5 ? underfi: underflow error interrupt flag this flag is set when an underflow error occurs for an isochronous endpoint.this underfi flag can generate a ?usb endpoint interrupt? if flerre bit is set. writing this bit to zero acknowl- edges the interrupt source (usb clocks must be enabled before). writing this bit to one has no effect. see ?isochronous mode? on page 207 for more details. ? bit 4 ? res: reserved this bit is reserved and will always read as zero. ? bit 3:2 ? dtseq[1:0]: data toggle sequencing flag these flags are set by hardware to indicate the pid data of the current bank as shown in table 21-5 . for out transfer, this value indicates the last da ta toggle received on the current bank. for in transfer, it indicates the toggle that will be used for the next packet to be sent. this is not rela- tive to the current bank. bit 7 6 5 4 3 2 1 0 (0xee) cfgok overfi underfi - dtseq1:0 nbusybk1:0 uesta0x read/write r r/w r/w r r r r r initial value 0 0 0 0 0 0 0 0 table 21-5. dtseq[1:0] bits settings dtseq1 dtseq1 pid data 00 data0 01 data1 10 reserved. 11
218 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 1:0 ? nbusybk[1:0]: busy bank flag these flags are set by hardware to indicate the number of busy bank for the selected endpoint as shown in table 21-6 . for in endpoint, it indicates the number of busy bank(s), filled by the user, ready for in transfer. for out endpoint, it indicates the number of busy bank(s) filled by out transaction from the host. 21.18.14 uesta1x ? usb endpoint status 1 register ? bits 7:3 ? res: reserved these bits are reserved and will always read as zero. ? bit 2 ? ctrldir: control direction this flag is updated by the usb controller wh en a setup packet has been received. this flag bit can be used for debug purpose to give the direction of the following packet. reading one from this flag means that the following packet is for an in request, reading zero for an out request. ? bits 1:0 ? currbk[1:0]: current bank these flags are set by hardware to indicate the current bank number in used with the selected endpoint as shown in table 21-6 . these flags are not relevant for control endpoint (control end- point can not be configured in dual bank mode).these flags can be used for debug purpose and are optional for data transfer with endpoint in dual bank mode. table 21-6. nbusybk[1:0] bits settings nbusybk1 nbusybk0 number of busy banks 00 all banks are free 01 1 busy bank 10 2 busy banks 11 reserved bit 76543 2 1 0 (0xef) - - - - - ctrldir currbk[1:0] uesta1x read/write r r r r r r r initial value 0 0 0 0 0 0 0 0 table 21-7. currbk[1:0] bits settings currbk1 currbk0 current bank number 00 bank 0 01 bank 1 10 reserved 11
219 7799d?avr?11/10 atmega8u2/16u2/32u2 21.18.15 ueintx ? usb endpoint interrupt register ? bit 7 ? fifocon: fifo control bit this bit can only be written to zero by software. writing this bit to one has no effect. the behav- ior of this bit depends on the direction of the selected endpoint. ? for out or control endpoints: this flag is set by the usb controller when a new out message is stored in the current bank. in this situation rxout or rxstp flags are also updated at the same time. writing this bit to zero frees the current bank and switches to the next bank. ? for in endpoints: this flag is set by the usb controller when the current bank is free and can be loaded with new data bytes. in this situation txin flag is also updated at the same time. writing this bit to zero sends the fifo content and to switch the next bank. ? bit 6 ? nakini: nak in received interrupt flag this flag is set when a nak handshake has been sent in response to a in request from the host. this nakini flag can generate a ?usb endpoint interrupt? if nakine bit is set. writing this bit to zero acknowledges the interrupt source (usb clocks must be enabled before). writing this bit to one has no effect. ? bit 5 ? rwal: read/write allowed flag this flag is set by the usb controller and is relevant for all endpoint types except control end- point. for an in endpoint, this flag is set when the current bank is not full i.e. the firmware can push at least one more byte into the fifo (updatx register). for an out endpoint, this flag is set when the current bank is not empty i.e. the firmware can read from the fifo (updatx regis- ter). when the stallrq bit is set or one of the endpoint error is set, this flag can not be set. ? bit 4 ? nakouti: nak out received interrupt flag this flag is set by the usb controller when a nak handshake has been sent in response of a out request from the host. this nakouti flag can generate a ?usb endpoint interrupt? if nakoute bit is set. writing this bit to zero acknowledges the interrupt source (usb clocks must be enabled before). writing this bit to one has no effect. ? bit 3 ? rxstpi: received setup interrupt flag this flag is set by the usb controller when a new valid (error free) setup packet has been received from the host. this rxstpi flag can generate a ?usb endpoint interrupt? if rxstpe bit is set. writing this bit to zero acknowledges the interrupt so urce (usb clocks must be enabled before). writing this bit to one has no effect. ? bit 2 ? rxouti / killbk: received out data interrupt flag depending on the direction of the endpoint, this bit has two functions: ? endpoint out direction (rxouti flag): bit 76543210 (0xe8) fifocon nakini rwal nakouti rxstpi rxouti stalledi txini ueintx read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 00000
220 7799d?avr?11/10 atmega8u2/16u2/32u2 this flag is set by the usb controller when the current bank contains a new packet. this rxouti flag can generate a ?usb endpoint interrupt? if rxoute bit is set. writing this bit to zero acknowledges the interrupt source (usb clocks must be enabled before). writing this bit to one has no effect for an out endpoint. ? endpoint in direction (killbk bit) writing this bit to one kills the last loaded bank. this sequence can be used to cancelled a previ- ously loaded endpoint. clearing by software has no effect. see page 206 for more details on the abort. ? bit 1 ? stalledi: stalledi interrupt flag this flag is set by the usb controller when stall handshake has been sent, or when a crc error has been detected for an isochronous out endpoint. this stalledi flag can generate a ?usb endpoint interrupt? if stallede bit is set. writing this bit to zero acknowledges the inter- rupt source (usb clocks must be enabled before). writing this bit to one has no effect. ? bit 0 ? txini: transmitter ready interrupt flag this flag is set by the usb controller when the current bank is free and can be filled. this txini flag can generate a ?usb endpoint interrupt? if txine bit is set. writing this bit to zero acknowl- edges the interrupt source (usb clocks must be enabled before). writing this bit to one has no effect. 21.18.16 ueienx ? usb endpoint interrupt enable register ? bit 7 ? flerre: flow error interrupt enable flag writing this bit to one enables interrupt on overfi or underfi flags. an overflow or underflow interrupt will be generated only if the flerre bit is set to one, the global interrupt flag in sreg is written to one, and the overfi or underfi flags are set. ? bit 6 ? nakine: nak in interrupt enable bit writing this bit to one enables interrupt on nakini flag. a nak in interrupt will be generated only if the nakine bit is set to one, the global interrupt flag in sreg is written to one, and the nakini is set. ? bit 5 ? res: reserved this bit is reserved and will always read as zero. ? bit 4 ? nakoute: nak out interrupt enable bit writing this bit to one enables interrupt on nakouti flag. a nakout interrupt will be generated only if the nakoute bit is set to one, the global interrupt flag in sreg is written to one, and the nakouti is set. bit 76543210 (0xf0) flerre nakine - nakoute rxstpe rxoute stallede txine ueienx read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 0 00000
221 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 3 ? rxstpe: received setup interrupt enable flag writing this bit to one enables interrupt on rxstpi flag. a received setup interrupt will be gener- ated only if the rxstpe bit is set to one, the global interrupt flag in sreg is written to one, and the rxstpi is set. ? bit 2 ? rxoute: received out data interrupt enable flag writing this bit to one enables interrupt on rxouti flag. a received out interrupt will be gener- ated only if the rxoute bit is set to one, the global interrupt flag in sreg is written to one, and the rxouti is set. ? bit 1 ? stallede: stalled interrupt enable flag writing this bit to one enables interrupt on stalledi flag. a sent stall interrupt will be gener- ated only if the stallede bit is set to one, the global interrupt flag in sreg is written to one, and the stalledi is set. ? bit 0 ? txine: transmitter ready interrupt enable flag writing this bit to one enables interrupt on txini flag. a transmitter ready interrupt will be gener- ated only if the txine bit is set to one, the global interrupt flag in sreg is written to one, and the txini is set. 21.18.17 uedatx ? usb data endpoint register ? bits 7:0 ? dat[7:0]: data bits the usb data endpoint register is a read/write register used for data transfer between the reg- ister file and the usb device controller. writing to the register pushes the data byte into the current bank of the selected endpoint. reading the register pops extracts one data byte from the current bank of the selected endpoint. 21.18.18 uebclx ? usb endpoint byte count register ? bits 7:0 ? byct[7:0]:byte count bits this register is read only. its content is updated by the usb controller. ? for in endpoint: this register contains the number of byte currently loaded into the current bank of the selected endpoint. the content of this register is incremented after each write access to the endpoint data register. ? for out endpoint: bit 76543210 (0xf1) dat d7 dat d6 dat d5 dat d4 dat d3 dat d2 dat d1 dat d0 uedatx read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 000000 bit 76543210 (0xf2) byct d7 byct d6 byct d5 byct d4 byct d3 byct d2 byct d1 byct d0 uebclx read/write r r r r r r r r r initial value 0 0 000000
222 7799d?avr?11/10 atmega8u2/16u2/32u2 this register contains the number of received byte into the current bank of the selected end- point. the content of this register is decremented after each write access to the endpoint data register. 21.18.19 ueint ? usb endpoint number interrupt register ? bits 7:5 ? res: reserved the value read from these bits is always 0. do not set these bits. ? bits 4:0 ? epint[4:0]: endpoint interrupts bits these flags are updated by the usb controller when a usb endpoint interrupt occurs (at least one bit in ueintx set). each bit in this field indicates whic h endpoint number has generated a usb endpoint interrupt request. each one of these bits are independently cleared by hardware when their respective interrupt source is served. bit 76543210 (0xf4) - - - epint4:0 ueint read/write r r r r r r r r r initial value 0 0 0 0 0 0 0 0
223 7799d?avr?11/10 atmega8u2/16u2/32u2 22. analog comparator 22.1 overview the analog comparator compares the input values on the positive pin ain0 and negative pin ain1. when the voltage on the positive pin ain0 is higher than the voltage on the negative pin ain1, the analog comparator output, aco, is set. the comparator?s output can be set to trigger the timer/counter1 input capture function. in addition, the comparator can trigger a separate interrupt, exclusive to the analog comparator. the user can select interrupt triggering on com- parator output rise, fall or toggle. a block diagram of the comparator and its surrounding logic is shown in figure 22-1 . user can also replace by software the ain0 input by the internal bandgap reference. figure 22-1. analog comparator block diagram (1) notes: 1. refer to figure 1-1 on page 2 and table 12-9 on page 79 for analog comparator pin placement. acbg bandgap reference ain2 ain3 ain4 ain5 ain6 ain0 acmux
224 7799d?avr?11/10 atmega8u2/16u2/32u2 22.2 register description 22.2.1 acsr ? analog comparator control and status register ? bit 7 ? acd: analog comparator disable when this bit is written logic one, the power to the analog comparator is switched off. this bit can be set at any time to turn off the analog comparator. this will reduce power consumption in active and idle mode. when changing the acd bit, the analog comparator interrupt must be disabled by clearing the acie bit in acsr. otherwise an interrupt can occur when the bit is changed. ? bit 6 ? acbg: analog comparator bandgap select when this bit is set, a fixed bandgap reference voltage replaces the positive input to the analog comparator. when this bit is cleared, ain0 is applied to the positive input of the analog compar- ator. see ?internal voltage reference? on page 51. ? bit 5 ? aco: analog comparator output the output of the analog comparator is synchronized and then directly connected to aco. the synchronization introduces a delay of 1 - 2 clock cycles. ? bit 4 ? aci: analog comparator interrupt flag this bit is set by hardware when a comparator output event triggers the interrupt mode defined by acis1 and acis0. the analog comparator interrupt routine is executed if the acie bit is set and the i-bit in sreg is set. aci is cleared by hardware when executing the corresponding inter- rupt handling vector. alternatively, aci is cleared by writing a logic one to the flag. ? bit 3 ? acie: analog comparator interrupt enable when the acie bit is written logic one and the i-bit in the status register is set, the analog com- parator interrupt is activated. when written logic zero, the interrupt is disabled. ? bit 2 ? acic: analog comparator input capture enable when written logic one, this bit enables the input capture function in timer/counter1 to be trig- gered by the analog comparator. the comparator output is in this case directly connected to the input capture front-end logic, making the comparator utilize the noise canceler and edge select features of the timer/counter1 input capture int errupt. when written logic zero, no connection between the analog comparator and the input capture function exists. to make the comparator trigger the timer/counter1 input capture interrupt, the icie1 bit in the timer interrupt mask register (timsk1) must be set. ? bits 1, 0 ? acis1, acis0: analog comparator interrupt mode select these bits determine which comparator events that trigger the analog comparator interrupt. the different settings are shown in table 22-1 . bit 76543210 0x30 (0x50) acd acbg aco aci acie acic acis1 acis0 acsr read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 n/a 0 0 0 0 0
225 7799d?avr?11/10 atmega8u2/16u2/32u2 when changing the acis1/acis0 bits, the analog comparator interrupt must be disabled by clearing its interrupt enable bit in the acsr register. otherwise an interrupt can occur when the bits are changed. 22.2.2 acmux ? analog comparator input multiplexer ? bit 2, 0 ? cmux2:0: analog comparator selection bits the value of these bits selects which combination of analog inputs are connected to the analog comparator. the different settings are shown in table 22-2 . 22.2.3 didr1 ? digital input disable register 1 ? bit 1, 0 ? ain1d, ain0d: ain1, ain0 digital input disable when this bit is written logic one, the digital input buffer on the ainx pin is disabled. the corre- sponding pin register bit will always read as zero when this bit is set. when an analog signal is applied to the ain1/0 pin and the digital input from this pin is not needed, this bit should be writ- ten logic one to reduce power consumption in the digital input buffer. table 22-1. acis1/acis0 settings acis1 acis0 interrupt mode 0 0 comparator interrupt on output toggle. 0 1 reserved 1 0 comparator interrupt on falling output edge. 1 1 comparator interrupt on rising output edge. bit 76543210 (0x7d) ? ? ? ? ? cmux2 cmux1 cmux0 acmux read/write r r r r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 22-2. cmux2:0 settings cmux2 cmux1 cmux0 comparator input 0 0 0 ain1 0 0 1 ain2 0 1 0 ain3 0 1 1 ain4 1 0 0 ain5 1 0 1 ain6 1 1 0 reserved 1 1 1 reserved bit 76543210 ? ain6d ain5d ain4d ain3d ain2d ain1d ain0d didr1 read/write r r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
226 7799d?avr?11/10 atmega8u2/16u2/32u2 23. boot loader support ? read-while-write self-programming 23.1 features ? read-while-write self-programming ? flexible boot memory size ? high security (separate boot lock bits for a flexible protection) ? separate fuse to select reset vector ? optimized page (1) size ? code efficient algorithm ? efficient read-modify-write support note: 1. a page is a section in the flash consisting of several bytes (see table 25-7 on page 249 ) used during programming. the page organization does not affect normal operation. 23.2 overivew the boot loader support provides a real read-while-write self-programming mechanism for downloading and uploading program code by the mcu itself. this feature allows flexible applica- tion software updates controlled by the mcu using a flash-resident boot loader program. the boot loader program can use any available data interface and associated protocol to read code and write (program) that code into the flash memory, or read the code from the program mem- ory. the program code within the boot loader sect ion has the capability to write into the entire flash, including the boot loader memory. the boot loader can thus even modify itself, and it can also erase itself from the code if the feature is not needed anymore. the size of the boot loader memory is configurable with fuses and the boot loader has two separate sets of boot lock bits which can be set independently. this gives the user a unique flexibility to select differ- ent levels of protection. 23.3 application and boot loader flash sections the flash memory is organized in two main sections, the application section and the boot loader section (see figure 23-2 ). the size of the different sections is configured by the bootsz fuses as shown in table 23-8 on page 239 and figure 23-2 . these two sections can have different level of protection since they have different sets of lock bits. 23.3.1 application section the application section is the section of the flas h that is used for storing the application code. the protection level for the application section can be selected by the application boot lock bits (boot lock bits 0), see table 23-2 on page 230 . the application section can never store any boot loader code since the spm instruction is disabled when executed from the application section. 23.3.2 bls ? boot loader section while the application section is used for storing the application code, the the boot loader soft- ware must be located in the bls since the spm instruction can initiate a programming when executing from the bls only. the spm instruction can access the entire flash, including the bls itself. the protection level for the boot loader section can be selected by the boot loader lock bits (boot lock bits 1), see table 23-3 on page 230 .
227 7799d?avr?11/10 atmega8u2/16u2/32u2 23.4 read-while-write and no read-while-write flash sections whether the cpu supports read-while-write or if the cpu is halted during a boot loader soft- ware update is dependent on which address that is being programmed. in addition to the two sections that are configurable by the bootsz fuses as described above, the flash is also divided into two fixed sections, the read-while-write (rww) section and the no read-while- write (nrww) section. the limit between the rww- and nrww sections is given in table 23- 1 and figure 23-1 on page 228 . the main difference between the two sections is: ? when erasing or writing a page located inside the rww section, the nrww section can be read during the operation. ? when erasing or writing a page located inside the nrww section, the cpu is halted during the entire operation. note that the user software can never read any code that is located inside the rww section dur- ing a boot loader software operation. the syntax ?read-while-write section? refers to which section that is being programmed (erased or written), not which section that actually is being read during a boot loader software update. 23.4.1 rww ? read-while-write section if a boot loader software update is programming a page inside the rww section, it is possible to read code from the flash, but only code that is located in the nrww section. during an on- going programming, the software must ensure that the rww section never is being read. if the user software is trying to read code that is located inside the rww section (i.e., by load program memory, call, or jump instructions or an interr upt) during programming, the software might end up in an unknown state. to avoid this, the inte rrupts should either be disabled or moved to the boot loader section. the boot loader section is always located in the nrww section. the rww section busy bit (rwwsb) in the store program memory control and status register (spmcsr) will be read as logical one as long as the rww section is blocked for reading. after a programming is completed, the rwwsb must be cleared by software before reading code located in the rww section. see ?spmcsr ? store program memory control and status reg- ister? on page 242. for details on how to clear rwwsb. 23.4.2 nrww ? no read-while-write section the code located in the nrww section can be read when the boot loader software is updating a page in the rww section. when the boot loader code updates the nrww section, the cpu is halted during the entire page erase or page write operation. table 23-1. read-while-write features which section does the z-pointer address during the programming? which section can be read during programming? is the cpu halted? read-while-write supported? rww section nrww section no yes nrww section none yes no
228 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 23-1. read-while-write vs. no read-while-write read-while-write (rww) section no read-while-write (nrww) section z-pointer addresses rww section z-pointer addresses nrww section cpu is halted during the operation code located in nrww section can be read during the operation
229 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 23-2. memory sections note: 1. the parameters in the figure above are given in table 23-8 on page 239 . 23.5 boot loader lock bits if no boot loader capability is needed, the entire flash is available for application code. the boot loader has two separate sets of boot lock bits which can be set independently. this gives the user a unique flexibility to select different levels of protection. the user can select: ? to protect the entire flash from a software update by the mcu. ? to protect only the boot loader flash section from a software update by the mcu. ? to protect only the application flash section from a software update by the mcu. ? allow software update in the entire flash. see table 23-2 and table 23-3 for further details. the boot lock bits can be set in software and in serial or parallel programming mode, but they can be cleared by a chip erase command only. the general write lock (lock bit mode 2) does not control the programming of the flash memory by spm instruction. similarly, the general read/write lock (lock bit mode 1) does not control reading nor writing by (e)lpm/spm, if it is attempted. 0x0000 flashend pro g ram memory bootsz = '11' application flash section boot loader flash section flashend pro g ram memory bootsz = '10' 0x0000 pro g ram memory bootsz = '01' pro g ram memory bootsz = '00' application flash section boot loader flash section 0x0000 flashend application flash section flashend end rww start nrww application flash section boot loader flash section boot loader flash section end rww start nrww end rww start nrww 0x0000 end rww, end application start nrww, start boot loader application flash section application flash section application flash section read-while-write section no read-while-write section read-while-write section no read-while-write section read-while-write section no read-while-write section read-while-write section no read-while-write section end application start boot loader end application start boot loader end application start boot loader
230 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. ?1? means unprogrammed, ?0? means programmed note: 1. ?1? means unprogrammed, ?0? means programmed 23.6 entering the boot loader program the bootloader can be executed with three different conditions: 23.6.1 regular application conditions. a jump or call from the application program. this may be initiated by a trigger such as a com- mand received via usart, or spi interface. 23.6.2 boot reset fuse the boot reset fuse (bootrst) can be programmed so that the reset vector is pointing to the boot flash start address after a reset. in this case, the boot loader is started after a reset. after the application code is loaded, the program can start executing the application code. note that the fuses cannot be changed by the mcu itself. this means that once the boot reset fuse table 23-2. boot lock bit0 protection modes (application section) (1) blb0 mode blb02 blb01 protection 111 no restrictions for spm or (e)lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 300 spm is not allowed to write to the application section, and (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 401 (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. table 23-3. boot lock bit1 protection modes (boot loader section) (1) blb1 mode blb12 blb11 protection 111 no restrictions for spm or (e)lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to the boot loader section, and (e)lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. 401 (e)lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section.
231 7799d?avr?11/10 atmega8u2/16u2/32u2 is programmed, the reset vector will always point to the boot loader reset and the fuse can only be changed through the serial or parallel programming interface. note: 1. ?1? means unprogrammed, ?0? means programmed 23.6.3 external hardware conditions the hardware boot enable fuse (hwbe) can be programmed (see table 23-5 ) so that upon special hardware conditions under reset, the bootloader execution is forced after reset. note: 1. ?1? means unprogrammed, ?0? means programmed when the hwbe fuse is enable the pd7 / h w b pin is configured as input during reset and sam- pled during reset rising edge. when pd7 / hwb pin is ?0? during reset rising edge, the reset vector will be set as the boot loader reset address and the boot loader will be executed (see figures 23-3). table 23-4. boot reset fuse (1) bootrst reset address 1 reset vector = application reset (address 0x0000) 0 reset vector = boot loader reset (see table 23-8 on page 239 ) table 23-5. hardware boot enable fuse (1) hwbe reset address 1 pd7/ hwb pin can not be used to force boot loader execution after reset 0 pd7/ hwb pin is used during reset to force bootloader execution after reset
232 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 23-3. boot process description 23.7 addressing the flash during self-programming the z-pointer is used to address the spm commands. the z pointer consists of the z-registers zl and zh in the register file. the number of bits actually used is implementation dependent. since the flash is organized in pages (see table 25-7 on page 249 ), the program counter can be treated as having two different sections. one section, consisting of the least significant bits, is addressing the words within a page, while the most significant bits are addressing the pages. this is shown in figure 23-4 . note that the page erase and page write operations are addressed independently. therefore it is of major importance that the boot loader software addresses the same page in both the page erase and page write operation. once a program- ming operation is initiated, the address is latched and the z-pointer can be used for other operations. the (e)lpm instruction use the z-pointer to store the address. since this instruction addresses the flash byte-by-byte, also bit z0 of the z-pointer is used. hwbe bootrst  ext. hardware conditions  reset vector = application reset reset vector =boot lhoader reset  reset pd7/hwb t shrh t hhrh
233 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 23-4. addressing the flash during spm (1) note: 1. the different variables used in figure 23-4 are listed in table 23-10 on page 239 . 23.8 self-programming the flash the program memory is updated in a page by page fashion. before programming a page with the data stored in the temporary page buffer, the page must be erased. the temporary page buf- fer is filled one word at a time using spm and the buffer can be filled either before the page erase command or between a page erase and a page write operation: alternative 1, fill the buffer before a page erase ? fill temporary page buffer ? perform a page erase ? perform a page write alternative 2, fill the buffer after page erase ? perform a page erase ? fill temporary page buffer ? perform a page write if only a part of the page needs to be changed, the rest of the page must be stored (for example in the temporary page buffer) before the erase, and then be rewritten. when using alternative 1, the boot loader provides an effective read-modify-write feature which allows the user software to first read the page, do the necessary changes, and then write back the modified data. if alter- native 2 is used, it is not possible to read the old data while loading since the page is already erased. the temporary page buffer can be accessed in a random sequence. it is essential that the page address used in both the page erase and page write operation is addressing the same page. see ?simple assembly code example for a boot loader? on page 237 for an assembly code example. program memory 0 1 15 z - register bit 0 zpagemsb word address within a page page address within the flash zpcmsb instruction word pag e pcword[pagemsb:0]: 00 01 02 pageend pag e pcword pcpage pcmsb pagemsb program counter
234 7799d?avr?11/10 atmega8u2/16u2/32u2 23.8.1 performing page erase by spm to execute page erase, set up the address in the z-pointer, write ?x0000011? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage in the z-register. other bits in the z-pointer will be ignored during this operation. ? page erase to the rww section: the nrww section can be read during the page erase. ? page erase to the nrww section: the cpu is halted during the operation. 23.8.2 filling the temporary buffer (page loading) to write an instruction word, set up the address in the z-pointer and data in r1:r0, write ?00000001? to spmcsr and execute spm within f our clock cycles after writing spmcsr. the content of pcword in the z-regist er is used to address the data in the temporary buffer. the temporary buffer will auto-erase after a page wr ite operation or by writing the rwwsre bit in spmcsr. it is also erased after a system reset. note that it is not possible to write more than one time to each address without erasing the temporary buffer. if the eeprom is written in the middle of an spm page load operation, all data loaded will be lost. 23.8.3 performing a page write to execute page write, set up the address in the z-pointer, write ?x0000101? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage. other bits in the z-pointer must be written to zero during this operation. ? page write to the rww section: the nrww section can be read during the page write. ? page write to the nrww section: the cpu is halted during the operation. 23.8.4 using the spm interrupt if the spm interrupt is enabled, the spm interrupt will generate a constant interrupt when the spmen bit in spmcsr is cleared. this means that the interrupt can be used instead of polling the spmcsr register in software. when using the spm interrupt, the interrupt vectors should be moved to the bls section to avoid that an interrupt is accessing the rww section when it is blocked for reading. how to move the interrupts is described in ?interrupts? on page 64 . 23.8.5 consideration while updating bls special care must be taken if the user allows the boot loader section to be updated by leaving boot lock bit11 unprogrammed. an accidental write to the boot loader itself can corrupt the entire boot loader, and further software updates might be impossible. if it is not necessary to change the boot loader software itself, it is recommended to program the boot lock bit11 to protect the boot loader software from any internal software changes. 23.8.6 prevent reading the rww section during self-programming during self-programming (either page erase or page write), the rww section is always blocked for reading. the user software itself must prevent that this section is addressed during the self programming operation. the rwwsb in the spmcsr will be set as long as the rww section is busy. during self-programming the interrupt vector table should be moved to the bls as described in ?interrupts? on page 64 , or the interrupts must be disabled. before addressing the rww section after the programming is completed, the user software must clear the rwwsb by writing the rwwsre. see ?simple assembly code example for a boot loader? on
235 7799d?avr?11/10 atmega8u2/16u2/32u2 page 237 for an example. 23.8.7 setting the boot loader lock bits by spm to set the boot loader lock bits, write the desired data to r0, write ?x0001001? to spmcsr and execute spm within four clock cycles after writing spmcsr. the only accessible lock bits are the boot lock bits that may prevent the application and boot loader section from any soft- ware update by the mcu. see table 23-2 and table 23-3 for how the different settings of the boot loader bits affect the flash access. if bits 5..2 in r0 are cleared (zero), the corresponding boot lock bit will be programmed if an spm instruction is executed within four cycles after blbset and spmen are set in spmcsr. the z-pointer is don?t care during this operation, but for future compatibility it is recommended to load the z-pointer with 0x0001 (same as used for reading the lo ck bits). for future compatibility it is also recommended to set bits 7, 6, 1, and 0 in r0 to ?1? when writing the lock bits. when pro- gramming the lock bits the entire flash can be read during the operation. 23.8.8 eeprom write prevents writing to spmcsr note that an eeprom write operation will block all software programming to flash. reading the fuses and lock bits from software will also be prevented during the eeprom write operation. it is recommended that the user checks the status bit (eepe) in the eecr register and verifies that the bit is cleared before writing to the spmcsr register. 23.8.9 reading the fuse and lock bits from software it is possible to read both the fuse and lock bits from software. to read the lock bits, load the z-pointer with 0x0001 and set the blbset and spmen bits in spmcsr. when an (e)lpm instruction is executed within three cpu cycles after the blbset and spmen bits are set in spmcsr, the value of the lock bits will be loaded in the destination register. the blbset and spmen bits will auto-clear upon completion of reading the lock bits or if no (e)lpm instruction is executed within three cpu cycles or no spm ins truction is executed within four cpu cycles. when blbset and spmen are cleared, (e)lpm will work as described in the instruction set manual. the algorithm for reading the fuse low byte is similar to the one described above for reading the lock bits. to read the fuse low byte, load the z-pointer with 0x0000 and set the blbset and spmen bits in spmcsr. when an (e)lpm instruction is executed within three cycles after the blbset and spmen bits are set in the spmcsr, the value of the fuse low byte (flb) will be loaded in the destination register as shown below. refer to table 25-5 on page 248 for a detailed description and mapping of the fuse low byte. similarly, when reading the fuse high byte, load 0x0003 in the z-pointer. when an (e)lpm instruction is executed within three cycles after the blbset and spmen bits are set in the spmcsr, the value of the fuse high byte (fhb) will be loaded in the destination register as bit 76543210 r0 1 1 blb12 blb11 blb02 blb01 1 1 bit 76543210 rd ? ? blb12 blb11 blb02 blb01 lb2 lb1 bit 7654 3210 rd flb7 flb6 flb5 flb4 flb3 flb2 flb1 flb0
236 7799d?avr?11/10 atmega8u2/16u2/32u2 shown below. refer to table 25-4 on page 248 for detailed description and mapping of the fuse high byte. when reading the extended fuse byte, load 0x0002 in the z-pointer. when an (e)lpm instruc- tion is executed within three cycles after the blbset and spmen bits are set in the spmcsr, the value of the extended fuse byte (efb) will be loaded in the destination register as shown below. refer to table 25-3 on page 247 for detailed description and mapping of the extended fuse byte. fuse and lock bits that are programmed, will be read as zero. fuse and lock bits that are unprogrammed, will be read as one. 23.8.10 reading the signature row from software to read the signature row from software, load the z-pointer with the signature byte address given in table 23-6 on page 236 and set the sigrd and spmen bits in spmcsr. when an lpm instruction is executed within three cpu cycles after the sigrd and spmen bits are set in spmcsr, the signature byte value will be loaded in the destination register. the sigrd and spmen bits will auto-clear upon completion of reading the signature row lock bits or if no lpm instruction is executed within three cpu cycles. when sigrd and spmen are cleared, lpm will work as described in the instruction set manual atmega8u2/16u2/32u2 includes a unique 10 bytes serial number located in the signature row. this unique serial number can be used as a usb serial number in the device enumeration pro- cess. the pointer addresses to access this unique serial number are given in table 23-6 on page 236 .. note: all other addresses are reserved for future use. 23.8.11 preventing flash corruption during periods of low v cc , the flash program can be corrupted because the supply voltage is too low for the cpu and the flash to operate properly. these issues are the same as for board level systems using the flash, and the same design solutions should be applied. a flash program corruption can be caused by two situations when the voltage is too low. first, a regular write sequence to the flash requires a minimum voltage to operate correctly. secondly, the cpu itself can execute instructions incorrectly, if the supply voltage for executing instructions is too low. bit 7654 3210 rd fhb7 fhb6 fhb5 fhb4 fhb3 fhb2 fhb1 fhb0 bit 7654 3210 rd ? ? ? ? ? efb2 efb1 efb0 table 23-6. signature row addressing signature byte z-pointer address device signature byte 1 0x0000 device signature byte 2 0x0002 device signature byte 3 0x0004 rc oscillator calibration byte 0x0001 unique serial number from 0x000e to 0x0018
237 7799d?avr?11/10 atmega8u2/16u2/32u2 flash corruption can easily be avoided by following these design recommendations (one is sufficient): 1. if there is no need for a boot loader update in the system, program the boot loader lock bits to prevent any boot loader software updates. 2. keep the avr reset active (low) during periods of insufficient power supply voltage. this can be done by enabling the internal brown-out detector (bod) if the operating voltage matches the detection level. if not, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient. 3. keep the avr core in power-down sleep mode during periods of low v cc . this will pre- vent the cpu from attempting to decode and execute instructions, effectively protecting the spmcsr register and thus the flash from unintentional writes. 23.8.12 programming time for flash when using spm the calibrated rc oscillator is used to time flash accesses. table 23-7 shows the typical pro- gramming time for flash accesses from the cpu. 23.8.13 simple assembly code example for a boot loader ;-the routine writes one page of data from ram to flash ; the first data location in ram is pointed to by the y pointer ; the first data location in flash is pointed to by the z-pointer ;-error handling is not included ;-the routine must be placed inside the boot space ; (at least the do_spm sub routine). only code inside nrww section can ; be read during self-programming (page erase and page write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcrval (r20) ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-it is assumed that either the interrupt table is moved to the boot ; loader section or that the interrupts are disabled. .equ pagesizeb = pagesize*2 ;pagesizeb is page size in bytes, not words .org smallbootstart write_page: ; page erase ldi spmcrval, (1< 238 7799d?avr?11/10 atmega8u2/16u2/32u2 call do_spm adiw zh:zl, 2 sbiw loophi:looplo, 2 ;use subi for pagesizeb<=256 brne wrloop ; execute page write subi zl, low(pagesizeb) ;restore pointer sbci zh, high(pagesizeb) ;not required for pagesizeb<=256 ldi spmcrval, (1< 239 7799d?avr?11/10 atmega8u2/16u2/32u2 23.8.14 atmega8u2 boot loader parameters in table 23-8 through table 23-10 , the parameters used in the description of the self-programming are given. (page size = 64 words = 128 bytes) note: 1. the different bootsz fuse configurations are shown in figure 23-2 . note: 1. for details about these two section, see ?nrww ? no read-while-write section? on page 227 and ?rww ? read-while- write section? on page 227 . note: 1. z0: should be zero for all spm commands, byte select for the (e)lpm instruction. see ?addressing the flash during self-programming? on page 232 for details about the use of z-pointer during self- programming. table 23-8. boot size configuration (1) (word addresses) bootsz1 bootsz0 boot size pages application flash section boot loader flash section end application section boot reset address (start boot loader section) 1 1 256 words 4 0x0000 - 0xeff 0xf00 - 0xfff 0xeff 0xf00 1 0 512 words 8 0x0000 - 0xdff 0xe00 - 0xfff 0xdff 0xe00 0 1 1024 words 16 0x0000 - 0xbff 0xc00 - 0xfff 0xbff 0xc00 0 0 2048 words 32 0x0000 - 0x7ff 0x800 - 0xfff 0x7ff 0x800 table 23-9. read-while-write limit (1) section pages address read-while-write section (rww) 32 0x0000 - 0x07ff no read-while-write section (nrww) 32 0x0800 - 0x0fff table 23-10. explanation of different variables used in figure 23-4 and the mapping to the z-pointer variable corresponding z-value description (1) pcmsb 12 most significant bit in the program counter. (the program counter is 13 bits pc[12:0]) pagemsb 5 most significant bit which is used to address the words within one page (64 words in a page requires six bits pc [5:0]). zpcmsb z13 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpcmsb equals pcmsb + 1. zpagemsb z6 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpagemsb equals pagemsb + 1. pcpage pc[12:6] z13:z7 program counter page address: page select, for page erase and page write pcword pc[5:0] z6:z1 program counter word address: word select, for filling temporary buffer (must be zero during page write operation)
240 7799d?avr?11/10 atmega8u2/16u2/32u2 23.8.15 atmega16u2 boot loader parameters in table 23-11 through table 23-13 , the parameters used in the description of the self-programming are given. (page size = 64 words = 128 bytes) note: 1. the different bootsz fuse configurations are shown in figure 23-2 . note: 1. for details about these two section, see ?nrww ? no read-while-write section? on page 227 and ?rww ? read-while- write section? on page 227 . note: 1. z0: should be zero for all spm commands, byte select for the (e)lpm instruction. see ?addressing the flash during self-programming? on page 232 for details about the use of z-pointer during self- programming. table 23-11. boot size configuration (1) (word addresses) bootsz1 bootsz0 boot size pages application flash section boot loader flash section end application section boot reset address (start boot loader section) 1 1 256 words 4 0x0000 - 0x1eff 0x1f00 - 0x1fff 0x1eff 0x1f00 1 0 512 words 8 0x0000 - 0x1dff 0x1e00 - 0x1fff 0x1dff 0x1e00 0 1 1024 words 16 0x0000 - 0x1bff 0x1c00 - 0x1fff 0x1bff 0x1c00 0 0 2048 words 32 0x0000 - 0x17ff 0x1800 - 0x1fff 0x17ff 0x1800 table 23-12. read-while-write limit (1) section pages address read-while-write section (rww) 96 0x0000 - 0x17ff no read-while-write section (nrww) 32 0x1800 - 0x1fff table 23-13. explanation of different variables used in figure 23-4 and the mapping to the z-pointer variable corresponding z-value description (1) pcmsb 12 most significant bit in the program counter. (the program counter is 13 bits pc[12:0]) pagemsb 5 most significant bit which is used to address the words within one page (64 words in a page requires six bits pc [5:0]). zpcmsb z13 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpcmsb equals pcmsb + 1. zpagemsb z6 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpagemsb equals pagemsb + 1. pcpage pc[12:6] z13:z7 program counter page address: page select, for page erase and page write pcword pc[5:0] z6:z1 program counter word address: word select, for filling temporary buffer (must be zero during page write operation)
241 7799d?avr?11/10 atmega8u2/16u2/32u2 23.8.16 atmega32u2 boot loader parameters in table 23-14 through table 23-16 , the parameters used in the description of the self-programming are given. (page size = 64 words = 128 bytes) note: 1. the different bootsz fuse configurations are shown in figure 23-2 . note: 1. for details about these two section, see ?nrww ? no read-while-write section? on page 227 and ?rww ? read-while- write section? on page 227 . note: 1. z0: should be zero for all spm commands, byte select for the (e)lpm instruction. see ?addressing the flash during self-programming? on page 232 for details about the use of z-pointer during self- programming. table 23-14. boot size configuration (1) (word addresses) bootsz1 bootsz0 boot size pages application flash section boot loader flash section end application section boot reset address (start boot loader section) 1 1 256 words 4 0x0000 - 0x3eff 0x3f00 - 0x3fff 0x3eff 0x3f00 1 0 512 words 8 0x0000 - 0x3dff 0x3e00 - 0x3fff 0x3dff 0x3e00 0 1 1024 words 16 0x0000 - 0x3bff 0x3c00 - 0x3fff 0x3bff 0x3c00 0 0 2048 words 32 0x0000 - 0x37ff 0x3800 - 0x3fff 0x37ff 0x3800 table 23-15. read-while-write limit (1) section pages address read-while-write section (rww) 224 0x0000 - 0x37ff no read-while-write section (nrww) 32 0x3800 - 0x3fff table 23-16. explanation of different variables used in figure 23-4 and the mapping to the z-pointer variable corresponding z-value description (1) pcmsb 12 most significant bit in the program counter. (the program counter is 13 bits pc[12:0]) pagemsb 5 most significant bit which is used to address the words within one page (64 words in a page requires six bits pc [5:0]). zpcmsb z13 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpcmsb equals pcmsb + 1. zpagemsb z6 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpagemsb equals pagemsb + 1. pcpage pc[12:6] z13:z7 program counter page address: page select, for page erase and page write pcword pc[5:0] z6:z1 program counter word address: word select, for filling temporary buffer (must be zero during page write operation)
242 7799d?avr?11/10 atmega8u2/16u2/32u2 23.9 register description 23.9.1 spmcsr ? store program memory control and status register the store program memory control and status register contains the control bits needed to con- trol the boot loader operations. ? bit 7 ? spmie: spm interrupt enable when the spmie bit is written to one, and the i-bit in the status register is set (one), the spm ready interrupt will be enabled. the spm ready interrupt will be executed as long as the spmen bit in the spmcsr register is cleared. ? bit 6 ? rwwsb: read-while-write section busy when a self-programming (page erase or page write) operation to the rww section is initi- ated, the rwwsb will be set (one) by hardware. when the rwwsb bit is set, the rww section cannot be accessed. the rwwsb bit will be cleared if the rwwsre bit is written to one after a self-programming operation is completed. alternatively the rwwsb bit will automatically be cleared if a page load operation is initiated. ? bit 5 ? sigrd: signature row read if this bit is written to one at the same time as spmen, the next lpm instruction within three clock cycles will read a byte from the signature row into the destination register. see ?reading the signature row from software? on page 236 for details. an spm instruction within four cycles after sigrd and spmen are set will have no effect. this operation is reserved for future use and should not be used. ? bit 4 ? rwwsre: read-while-write section read enable when programming (page erase or page write) to the rww section, the rww section is blocked for reading (the rwwsb will be set by hardware). to re-enable the rww section, the user software must wait until the programming is completed (spmen will be cleared). then, if the rwwsre bit is written to one at the same time as spmen, the next spm instruction within four clock cycles re-enables the rww section. the rww section cannot be re-enabled while the flash is busy with a page erase or a page write (spmen is set). if the rwwsre bit is writ- ten while the flash is being loaded, the flash load operation will abort and the data loaded will be lost. ? bit 3 ? blbset: boot lock bit set if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles sets boot lock bits, according to the data in r0. the data in r1 and the address in the z- pointer are ignored. the blbset bit will automatically be cleared upon completion of the lock bit set, or if no spm instruction is executed within four clock cycles. an (e)lpm instruction within three cycles after blbset and spmen are set in the spmcsr register, will read either the lock bits or the fuse bits (depending on z0 in the z-pointer) into the destination register. see ?reading the fuse and lock bits from software? on page 235 for details. bit 765 4 3 210 0x37 (0x57) spmie rwwsb sigrd rwwsre blbset pgwrt pgers spmen spmcsr read/write r/w r r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
243 7799d?avr?11/10 atmega8u2/16u2/32u2 ? bit 2 ? pgwrt: page write if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles executes page write, with the data stored in the temporary buffer. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgwrt bit will auto-clear upon completion of a page write, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page write operation if the nrww section is addressed. ? bit 1 ? pgers: page erase if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles executes page erase. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgers bit will auto-clear upon completion of a page erase, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page write operation if the nrww section is addressed. ? bit 0 ? spmen: store program memory enable this bit enables the spm instruction for the next four clock cycles. if written to one together with either rwwsre, blbset, pgwrt? or pgers, the following spm instruction will have a spe- cial meaning, see description above. if only spmen is written, the following spm instruction will store the value in r1:r0 in the temporary page buffer addressed by the z-pointer. the lsb of the z-pointer is ignored. the spmen bit will auto-clear upon completion of an spm instruction, or if no spm instruction is executed within four clock cycles. during page erase and page write, the spmen bit remains high until the operation is completed. writing any other combination than ?10001?, ?01001?, ?00101?, ?0 0011? or ?00001? in the lower five bits will have no effect. note: only one spm instruction should be active at any time.
244 7799d?avr?11/10 atmega8u2/16u2/32u2 24. debugwire on-chip debug system 24.1 features ? complete program flow control ? emulates all on-chip functions, both digital and analog, except reset pin ? real-time operation ? symbolic debugging support (both at c and assembler source level, or for other hlls) ? unlimited number of program break points (using software break points) ? non-intrusive operation ? electrical characteristics identical to real device ? automatic configuration system ? high-speed operation ? programming of non-volatile memories 24.2 overview the debugwire on-chip debug system uses a one-wir e, bi-directional interface to control the program flow, execute avr instructions in the cpu and to program the different non-volatile memories. 24.3 physical interface when the debugwire enable (dwen) fuse is programmed and lock bits are unprogrammed, the debugwire system within the target device is activated. the reset port pin is configured as a wire-and (open-drain) bi-directional i/o pin and becomes the communication gateway between target and emulator. figure 24-1. the debugwire setup figure 24-1 shows the schematic of a target mcu, with debugwire enabled, and the emulator connector. the system clock is not affected by debugwire and will always be the clock source selected by the cksel fuses. d w g nd d w ( r eset ) v cc 2 . 7 - 5 . 5 ( s ee n o t e )
245 7799d?avr?11/10 atmega8u2/16u2/32u2 when designing a system where debugwire will be used, the following observations must be made for correct operation: ? connecting the reset pin directly to v cc will not work. ? any capacitors (or additionnal circuitry) connected to the reset pin must be disconnected when using debugwire. ? all external reset sources must be disconnected. note: some releases of jtag ice mkii firmware may require a pull-up resistor with a value between 8 and 14 kohms when operating at 5v. 24.4 software break points debugwire supports program memory break points by the avr break instruction. setting a break point in avr studio ? will insert a break instruction in the program memory. the instruc- tion replaced by the break instruction will be stored. when program execution is continued, the stored instruction will be executed before continuing from the program memory. a break can be inserted manually by putting the break instruction in the program. the flash must be re-programmed each time a break point is changed. this is automatically handled by avr studio through the debugwire interface. the use of break points will therefore reduce the flash data retention. devices used for debugging purposes should not be shipped to end customers. 24.5 limitations of debugwire the debugwire communication pin (dw) is physically located on the same pin as external reset (reset). an external re set source is therefore not su pported when the debugwire is enabled. the debugwire system accurately emulates all i/o functions when running at full speed, i.e., when the program in the cpu is running. when th e cpu is stopped, care must be taken while accessing some of the i/o registers via the debugger (avr studio). a programmed dwen fuse enables some parts of the clock system to be running in all sleep modes. this will increase the power consumption while in sleep. thus, the dwen fuse should be disabled when debugwire is not used. 24.6 register description 24.6.1 dwdr ? debugwire data register the dwdr register provides a communication channel from the running program in the mcu to the debugger. this register is only accessible by the debugwire and can therefore not be used as a general purpose register in the normal operations. bit 76543210 0x31 (0x51) dwdr[7:0] dwdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
246 7799d?avr?11/10 atmega8u2/16u2/32u2 25. memory programming 25.1 program and data memory lock bits the atmega8u2/16u2/32u2 provides six lock bits which can be left unprogrammed (?1?) or can be programmed (?0?) to obtain the additional features listed in table 25-2 . the lock bits can only be erased to ?1? with the chip erase command. note: 1. ?1? means unprogrammed, ?0? means programmed table 25-1. lock bit byte (1) lock bit byte bit no description default value 7 ? 1 (unprogrammed) 6 ? 1 (unprogrammed) blb12 5 boot lock bit 1 (unprogrammed) blb11 4 boot lock bit 0 (programmed) blb02 3 boot lock bit 1 (unprogrammed) blb01 2 boot lock bit 1 (unprogrammed) lb2 1 lock bit 0 (programmed) lb1 0 lock bit 0 (programmed) table 25-2. lock bit protection modes (1)(2) memory lock bits protection type lb mode lb2 lb1 1 1 1 no memory lock features enabled. 210 further programming of the flash and eeprom is disabled in parallel and serial programming mode. the fuse bits are locked in both serial and parallel programming mode. (1) 300 further programming and verification of the flash and eeprom is disabled in parallel and serial programming mode. the boot lock bits and fuse bits are locked in both serial and parallel programming mode. (1) blb0 mode blb02 blb01 111 no restrictions for spm or (e)lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 300 spm is not allowed to write to the application section, and (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 401 (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section.
247 7799d?avr?11/10 atmega8u2/16u2/32u2 notes: 1. program the fuse bits and boot lock bits before programming the lb1 and lb2. 2. ?1? means unprogrammed, ?0? means programmed 25.2 fuse bits the atmega8u2/16u2/32u2 has three fuse bytes. table 25-3 - table 25-5 describe briefly the functionality of all the fuses and how they are mapped into the fuse bytes. note that the fuses are read as logical zero, ?0?, if they are programmed. note: 1. see ?system and reset characteristics? on page 267 for bodlevel fuse decoding. blb1 mode blb12 blb11 111 no restrictions for spm or (e)lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to the boot loader section, and (e)lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. 401 (e)lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. table 25-2. lock bit protection modes (1)(2) (continued) memory lock bits protection type table 25-3. extended fuse byte fuse low byte bit no description default value : 0xf4 ?7? 1 ?6? 1 ?5? 1 ?4? 1 hwbe 3 hardware boot enable 0 (programmed) bodlevel2 (1) 2 brown-out detector trigger level 1 (unprogrammed) bodlevel1 (1) 1 brown-out detector trigger level 0 (programmed) bodlevel0 (1) 0 brown-out detector trigger level 0 (programmed)
248 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. the spien fuse is not accessible in serial programming mode. 2. the default value of bootsz1..0 results in maximum boot size. see table 23-8 on page 239 for details. 3. see ?wdtcsr ? watchdog timer control register? on page 56 for details. 4. never ship a product with the dwen fuse programmed regardless of the setting of lock bits and rstdsbl fuse. a programmed dwen fuse enables some parts of the clock system to be running in all sleep modes. this may increase the power consumption. note: 1. the default value of sut1..0 results in maximum start-up time for the default clock source. see ?system and reset characteristics? on page 267 for details. 2. the default setting of cksel3..0 results in external crystal oscillator 8mhz. see table 8-1 on page 29 for details. 3. the ckout fuse allow the system clock to be output on portc7. see ?clock output buffer? on page 35 for details. 4. see ?system clock prescaler? on page 35 for details. the status of the fuse bits is not affected by chip erase. note that the fuse bits are locked if lock bit1 (lb1) is programmed. program the fuse bits before programming the lock bits. table 25-4. fuse high byte fuse high byte bit no description default value : 0xd9 dwen (4) 7 enable debugwire (and disable reset capability 1 (unprogrammed, debugwire disabled) rstdsbl 6 disable reset (pin can be used as general purpose i/o) 1 (unprogrammed, reset enabled) spien (1) 5 enable serial program and data downloading 0 (programmed, spi prog. enabled) wdton (3) 4 watchdog timer always on 1 (unprogrammed) (3) eesave 3 eeprom memory is preserved through the chip erase 1 (unprogrammed, eeprom not preserved) bootsz1 2 select boot size (see table 25-9 for details) 0 (programmed) (2) bootsz0 1 select boot size (see table 25-9 for details) 0 (programmed) (2) bootrst 0 select bootloader address as reset vector 1 (unprogrammed, reset vector @0x0000) table 25-5. fuse low byte fuse low byte bit no description default value : 0x5e ckdiv8 (4) 7 divide clock by 8 0 (programmed) ckout (3) 6 clock output 1 (unprogrammed) sut1 5 select start-up time 0 (programmed) (1) sut0 4 select start-up time 1 (unprogrammed) (1) cksel3 3 select clock source 1 (unprogrammed) (2) cksel2 2 select clock source 1 (unprogrammed) (2) cksel1 1 select clock source 1 (unprogrammed) (2) cksel0 0 select clock source 0 (programmed) (2)
249 7799d?avr?11/10 atmega8u2/16u2/32u2 25.2.1 latching of fuses the fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves programming mode. this does not apply to the eesave fuse which will take e ffect once it is pr ogrammed. the fuses are also latched on power-up in normal mode. 25.3 signature bytes all atmel microcontrollers have a three-byte signature code which identifies the device. this code can be read in both serial and parallel mode, also when the device is locked. the three bytes reside in a separate address space. for the atmega8u2/16u2/32u2 the signature bytes are given in table 25-6 . 25.4 calibration byte the atmega8u2/16u2/32u2 has a byte calibration value for the internal rc oscillator. this byte resides in the high byte of address 0x000 in the signature address space. during reset, this byte is automatically written into the osccal regi ster to ensure correct frequency of the cali- brated rc oscillator. 25.5 page size table 25-6. device and jtag id part signature bytes address jtag 0x000 0x001 0x002 part number manufacture id atmega8u2 0x1e 0x93 0x89 9389 0x1f atmega16u2 0x1e 0x94 0x89 9489 0x1f atmega32u2 0x1e 0x95 0x8a 958a 0x1f table 25-7. no. of words in a page and no. of pages in the flash device flash size page size pcword no. of pages pcpage pcmsb atmega8u2 4k words (8kbytes) 32 words pc[4:0] 128 pc[11:6] 11 atmega16u2 8k words (16kbytes) 64 words pc[5:0] 128 pc[12:6] 12 atmega32u2 16k words (32kbytes) 64 words pc[5:0] 256 pc[13:6] 13 table 25-8. no. of bytes in a page and no. of pages in the eeprom device eeprom size page size pcword no. of pages pcpage eeamsb atmega8u2 256 bytes 4 bytes eea[1:0] 128 eea[8:2] 8 atmega16u2 512 bytes 4 bytes eea[1:0] 128 eea[8:2] 8 atmega32u2 1k bytes 4 bytes eea[1:0] 256 eea[9:2] 9
250 7799d?avr?11/10 atmega8u2/16u2/32u2 25.6 parallel programming parameters, pin mapping, and commands this section describes how to parallel program and verify flash program memory, eeprom data memory, memory lock bits, and fuse bits in the atmega8u2/16u2/32u2. pulses are assumed to be at least 250 ns unless otherwise noted. 25.6.1 signal names in this section, some pins of the atmega8u2/16u2/32u2 are referenced by signal names describing their functionality during parallel programming, see figure 25-1 and table 25-9 . pins not described in the following table are referenced by pin names. the xa1/xa0 pins determine the action executed when the xtal1 pin is given a positive pulse. the bit coding is shown in table 25-12 . when pulsing w r or o e, the command loaded determines the action executed. the different commands are shown in table 25-13 . figure 25-1. parallel programming (1) note: 1. unused pins should be left floating. table 25-9. pin name mapping signal name in programming mode pin name i/o function rdy/ bsy pd1 o 0: device is busy programming, 1: device is ready for new command. oe pd2 i output enable (active low). wr pd3 i write pulse (active low). bs1 pd4 i byte select 1. xa0 pd5 i xtal action bit 0 xa1 pd6 i xtal action bit 1 vcc +5v gnd xtal1 pd1 pd2 pd3 pd4 pd5 pd6 pb7:0 data reset pd7 +12 v bs1 xa0 xa1 oe rdy/bsy pagel pc6 wr bs2 avcc +5v
251 7799d?avr?11/10 atmega8u2/16u2/32u2 pagel pd7 i program memory and eeprom data page load. bs2 pc6 i byte select 2. data pb7-0 i/o bi-directional data bus (output when oe is low). table 25-10. bs2 and bs1 encoding bs2 bs1 flash / eeprom address flash data loading / reading fuse programming reading fuse and lock bits 0 0 low byte low byte low byte fuse low byte 0 1 high byte high byte high byte lockbits 10 extended high byte reserved extended byte extended fuse byte 1 1 reserved reserved reserved fuse high byte table 25-11. pin values used to enter programming mode pin symbol value pagel prog_enable[3] 0 xa1 prog_enable[2] 0 xa0 prog_enable[1] 0 bs1 prog_enable[0] 0 table 25-12. xa1 and xa0 encoding xa1 xa0 action when xtal1 is pulsed 00 load flash or eeprom address (high or low address byte determined by bs2 and bs1). 0 1 load data (high or low data byte for flash determined by bs1). 1 0 load command 1 1 no action, idle table 25-13. command byte bit encoding command byte command executed 1000 0000 chip erase 0100 0000 write fuse bits 0010 0000 write lock bits 0001 0000 write flash table 25-9. pin name mapping signal name in programming mode pin name i/o function
252 7799d?avr?11/10 atmega8u2/16u2/32u2 25.7 parallel programming 25.7.1 enter programming mode the following algorithm puts the device in parallel programming mode: 1. apply 4.5 - 5.5v between v cc and gnd. 2. set reset to ?0? and toggle xtal1 at least six times. 3. set the prog_enable pins listed in table 25-11 on page 251 to ?0000? and wait at least 100 ns. 4. apply 11.5 - 12.5v to reset. any activity on prog_enable pins within 100 ns after +12v has been applied to reset, will cause the device to fail entering programming mode. 5. wait at least 50 s before sending a new command. 25.7.2 considerations for efficient programming the loaded command and address are retained in the device during programming. for efficient programming, the following should be considered. ? the command needs only be loaded once when writing or reading multiple memory locations. ? skip writing the data value 0xff, that is the contents of the entire eeprom (unless the eesave fuse is programmed) and flash after a chip erase. ? address high byte needs only be loaded before programming or reading a new 256 word window in flash or 256 byte eeprom. this consideration also applies to signature bytes reading. 25.7.3 chip erase the chip erase will erase the flash and eeprom (1) memories plus lock bits. the lock bits are not reset until the program memory has been completely erased. the fuse bits are not changed. a chip erase must be performed before the flash and/or eeprom are reprogrammed. note: 1. the eeprpom memory is preserved during chip erase if the eesave fuse is programmed. load command ?chip erase? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?1000 0000?. this is the command for chip erase. 4. give xtal1 a positive pulse. this loads the command. 5. give wr a negative pulse. this starts the chip erase. rdy/ bsy goes low. 0001 0001 write eeprom 0000 1000 read signature bytes and calibration byte 0000 0100 read fuse and lock bits 0000 0010 read flash 0000 0011 read eeprom table 25-13. command byte bit encoding command byte command executed
253 7799d?avr?11/10 atmega8u2/16u2/32u2 6. wait until rdy/ bsy goes high before loading a new command. 25.7.4 programming the flash the flash is organized in pages, see table 25-7 on page 249 . when programming the flash, the program data is latched into a page buffer. this allows one page of program data to be pro- grammed simultaneously. the following procedure describes how to program the entire flash memory: a. load command ?write flash? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?0001 0000?. this is the command for write flash. 4. give xtal1 a positive pulse. this loads the command. b. load address low byte (address bits 7..0) 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs2, bs1 to ?00?. this selects the address low byte. 3. set data = address low byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address low byte. c. load data low byte 1. set xa1, xa0 to ?01?. this enables data loading. 2. set data = data low byte (0x00 - 0xff). 3. give xtal1 a positive pulse. this loads the data byte. d. load data high byte 1. set bs1 to ?1?. this selects high data byte. 2. set xa1, xa0 to ?01?. this enables data loading. 3. set data = data high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the data byte. e. latch data 1. set bs1 to ?1?. this selects high data byte. 2. give pagel a positive pulse. this latches the data bytes. (see figure 25-3 for signal waveforms) f. repeat b through e until the entire buffer is filled or until all data within the page is loaded. while the lower bits in the address are mapped to words within the page, the higher bits address the pages within the flash. this is illustrated in figure 25-2 on page 254 . note that if less than eight bits are required to address words in the page (pagesize < 256), the most significant bit(s) in the address low byte are used to address the page when performing a page write. g. load address high byte (address bits15..8) 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs2, bs1 to ?01?. this selects the address high byte. 3. set data = address high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address high byte. h. load address extended high byte (address bits 23..16)
254 7799d?avr?11/10 atmega8u2/16u2/32u2 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs2, bs1 to ?10?. this selects the address extended high byte. 3. set data = address extended high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address high byte. i. program page 1. set bs2, bs1 to ?00? 2. give wr a negative pulse. this starts programming of the entire page of data. rdy/ bsy goes low. 3. wait until rdy/ bsy goes high (see figure 25-3 for signal waveforms). j. repeat b through i until the entire flash is programmed or until all data has been programmed. k. end page programming 1. 1. set xa1, xa0 to ?10?. this enables command loading. 2. set data to ?0000 0000?. this is the command for no operation. 3. give xtal1 a positive pulse. this loads the command, and the internal write signals are reset. figure 25-2. addressing the flash which is organized in pages (1) note: 1. pcpage and pcword are listed in table 25-7 on page 249 . program memory word address within a page page address within the flash instruction word pag e pcword[pagemsb:0]: 00 01 02 pageend pag e pcword pcpage pcmsb pagemsb program counter
255 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 25-3. programming the flash waveforms (1) note: 1. ?xx? is don?t care. the letters refer to the programming description above. 25.7.5 programming the eeprom the eeprom is organized in pages, see table 25-8 on page 249 . when programming the eeprom, the program data is latched into a page buffer. this allows one page of data to be programmed simultaneously. the programming algor ithm for the eeprom da ta memory is as follows (refer to ?programming the flash? on page 253 for details on command, address and data loading): 1. a: load command ?0001 0001?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. c: load data (0x00 - 0xff). 5. e: latch data (give pagel a positive pulse). k: repeat 3 through 5 until the entire buffer is filled. l: program eeprom page 1. set bs2, bs1 to ?00?. 2. give wr a negative pulse. this starts programming of the eeprom page. rdy/ bsy goes low. 3. wait until to rdy/ bsy goes high before programming the next page (see figure 25-4 for signal waveforms). rdy/bsy wr oe reset +12v pagel bs2 0x10 addr. low addr. high data data low data high addr. low data low data high xa1 xa0 bs1 xtal1 xx xx xx abcdeb cdeg f addr. ext.h h i
256 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 25-4. programming the eeprom waveforms 25.7.6 reading the flash the algorithm for reading the flash memory is as follows (refer to ?programming the flash? on page 253 for details on command and address loading): 1. a: load command ?0000 0010?. 2. h: load address extended byte (0x00- 0xff). 3. g: load address high byte (0x00 - 0xff). 4. b: load address low byte (0x00 - 0xff). 5. set oe to ?0?, and bs1 to ?0?. the flash word low byte can now be read at data. 6. set bs to ?1?. the flash word high byte can now be read at data. 7. set oe to ?1?. 25.7.7 reading the eeprom the algorithm for reading the eeprom memory is as follows (refer to ?programming the flash? on page 253 for details on command and address loading): 1. a: load command ?0000 0011?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0?. the eeprom data byte can now be read at data. 5. set oe to ?1?. 25.7.8 programming the fuse low bits the algorithm for programming the fuse low bits is as follows (refer to ?programming the flash? on page 253 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. give wr a negative pulse and wait for rdy/ bsy to go high. rdy/bsy wr oe reset +12v pagel bs2 0x11 addr. high data addr. low data addr. low data xx xa1 xa0 bs1 xtal1 xx agbceb c el k
257 7799d?avr?11/10 atmega8u2/16u2/32u2 25.7.9 programming the fuse high bits the algorithm for programming the fuse high bits is as follows (refer to ?programming the flash? on page 253 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs2, bs1 to ?01?. this selects high data byte. 4. give wr a negative pulse and wait for rdy/ bsy to go high. 5. set bs2, bs1 to ?00?. this selects low data byte. 25.7.10 programming the extended fuse bits the algorithm for programming the extended fuse bits is as follows (refer to ?programming the flash? on page 253 for details on command and data loading): 1. 1. a: load command ?0100 0000?. 2. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. 3. set bs2, bs1 to ?10?. this selects extended data byte. 4. 4. give wr a negative pulse and wait for rdy/ bsy to go high. 5. 5. set bs2, bs1 to ?00?. this selects low data byte. figure 25-5. programming the fuses waveforms 25.7.11 programming the lock bits the algorithm for programming the lock bits is as follows (refer to ?programming the flash? on page 253 for details on command and data loading): 1. a: load command ?0010 0000?. 2. c: load data low byte. bit n = ?0? programs the lock bit. if lb mode 3 is programmed (lb1 and lb2 is programmed), it is not possible to program the boot lock bits by any external programming mode. 3. give wr a negative pulse and wait for rdy/ bsy to go high. the lock bits can only be cleared by executing chip erase. rdy/bsy wr oe reset +12v pagel 0x40 data data xx xa1 xa0 bs1 xtal1 ac 0x40 data xx ac write fuse low byte write fuse high byte 0x40 data xx ac write extended fuse byte bs2
258 7799d?avr?11/10 atmega8u2/16u2/32u2 25.7.12 reading the fuse and lock bits the algorithm for reading the fuse and lock bits is as follows (refer to ?programming the flash? on page 253 for details on command loading): 1. a: load command ?0000 0100?. 2. set oe to ?0?, and bs2, bs1 to ?00?. the status of the fuse low bits can now be read at data (?0? means programmed). 3. set oe to ?0?, and bs2, bs1 to ?11?. the status of the fuse high bits can now be read at data (?0? means programmed). 4. set oe to ?0?, and bs2, bs1 to ?10?. the status of the extended fuse bits can now be read at data (?0? means programmed). 5. set oe to ?0?, and bs2, bs1 to ?01?. the status of the lock bits can now be read at data (?0? means programmed). 6. set oe to ?1?. figure 25-6. mapping between bs1, bs2 and the fuse and lock bits during read 25.7.13 reading the signature bytes the algorithm for reading the signature bytes is as follows (refer to ?programming the flash? on page 253 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte (0x00 - 0x02). 3. set oe to ?0?, and bs to ?0?. the selected signature byte can now be read at data. 4. set oe to ?1?. 25.7.14 reading the calibration byte the algorithm for reading the calibration byte is as follows (refer to ?programming the flash? on page 253 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte, 0x00. 3. set oe to ?0?, and bs1 to ?1?. the calibration byte can now be read at data. 4. set oe to ?1?. lock bits 0 1 bs2 fuse high byte 0 1 bs1 data fuse low byte 0 1 bs2 extended fuse byte
259 7799d?avr?11/10 atmega8u2/16u2/32u2 25.8 serial downloading both the flash and eeprom memory arrays ca n be programmed using a serial programming bus while reset is pulled to gnd. the serial programming interface consists of pins sck, pdi (input) and pdo (output). after reset is set low, the programming enable instruction needs to be executed first before program/eras e operations can be executed. note, in table 25-14 on page 259 , the pin mapping for serial programming is listed. not all packages use the spi pins dedicated for the internal serial peripheral interface - spi. 25.9 serial programming pin mapping figure 25-7. serial programming and verify (1) notes: 1. if the device is clocked by the internal oscillator, it is no need to connect a clock source to the xtal1 pin. 2. v cc - 0.3v < avcc < v cc + 0.3v, however, avcc should always be within 1.8 - 5.5v when programming the eeprom, an auto-erase cycle is built into the self-timed programming operation (in the serial mode only) and there is no need to first execute the chip erase instruction. the chip erase operation turns the content of every memory location in both the program and eeprom arrays into 0xff. depending on cksel fuses, a valid clock must be present. the minimum low and high periods for the serial clock (sck) input are defined as follows: low: > 2 cpu clock cycles for f ck < 12 mhz, 3 cpu clock cycles for f ck >= 12 mhz high: > 2 cpu clock cycles for f ck < 12 mhz, 3 cpu clock cycles for f ck >= 12 mhz table 25-14. pin mapping serial programming symbol pins i/o description pdi pb2 i serial data in pdo pb3 o serial data out sck pb1 i serial clock v cc g n d xtal1 sck pdo pdi reset +1. 8 - 5.5 v a v cc +1. 8 - 5.5 v (2)
260 7799d?avr?11/10 atmega8u2/16u2/32u2 25.9.1 serial programming algorithm when writing serial data to the atmega8u2/16u2/32u2, data is clocked on the rising edge of sck. when reading data from the atmega8u2/16u2/32u2, data is clocked on the falling edge of sck. see figure 25-8 for timing details. to program and verify the atmega8u2/16u2/32u2 in the serial programming mode, the follow- ing sequence is recommended (see four byte instruction formats in table 25-16 ): 1. power-up sequence: apply power between v cc and gnd while reset and sck are set to ?0?. in some sys- tems, the programmer can not guarantee that sck is held low during power-up. in this case, reset must be given a positive pulse of at least two cpu clock cycles duration after sck has been set to ?0?. 2. wait for at least 20 ms and enable serial programming by sending the programming enable serial instruction to pin pdi. 3. the serial programming instructions will not work if the communication is out of syn- chronization. when in sync. the second byte (0x53), will echo back when issuing the third byte of the programming enable instruction. whether the echo is correct or not, all four bytes of the instruction must be transmitted. if the 0x53 did not echo back, give reset a positive pulse and issue a new programming enable command. 4. the flash is programmed one page at a time. the memory page is loaded one byte at a time by supplying the 7 lsb of the address and data together with the load program memory page instruction. to ensure correct loading of the page, the data low byte must be loaded before data high byte is applied for a given address. the program memory page is stored by loading the write program memory page instruction with the address lines 15..8. before issuing this command, make sure the instruction load extended address byte has been used to define the msb of the address. the extended address byte is stored until the command is re-issued, i.e., the command needs only to be issued for the first page, since the memory size is not larger than 64kword. if polling ( rdy/ bsy ) is not used, the user must wait at least t wd_flash before issuing the next page. (see table 25-15 .) accessing the serial programming interface before the flash write operation completes can result in incorrect programming. 5. the eeprom array is programmed one byte at a time by supplying the address and data together with the appropriate write instruction. an eeprom memory location is first automatically erased before new data is written. if polling is not used, the user must wait at least t wd_eeprom before issuing the next byte. (see table 25-15 .) in a chip erased device, no 0xffs in the data file(s) need to be programmed. 6. any memory location can be verified by using the read instruction which returns the content at the selected address at serial output pdo. when reading the flash memory, use the instruction load extended address byte to define the upper address byte, which is not included in the read program memory instruction. the extended address byte is stored until the command is re-issued, i.e., the command needs only to be issued for the first page, since the memory size is not larger than 64kword. 7. at the end of the programming session, reset can be set high to commence normal operation. 8. power-off sequence (if needed): set reset to ?1?. turn v cc power off.
261 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 25-8. serial programming waveforms table 25-15. minimum wait delay before writing the next flash or eeprom location symbol minimum wait delay t wd_flash 4.5 ms t wd_eeprom 9.0 ms t wd_erase 9.0 ms msb msb lsb lsb serial clock input (sck) serial data input (mosi) (miso) sample serial data output
262 7799d?avr?11/10 atmega8u2/16u2/32u2 table 25-16. serial programming instruction set instruction instruction format operation byte 1 byte 2 byte 3 byte4 programming enable 1010 1100 0101 0011 xxxx xxxx xxxx xxxx enable serial programming after reset goes low. chip erase 1010 1100 100x xxxx xxxx xxxx xxxx xxxx chip erase eeprom and flash. load extended address byte 0100 1101 0000 0000 cccc cccc xxxx xxxx defines extended address byte for read program memory and write program memory page. read program memory 0010 h 000 aaaa aaaa bbbb bbbb oooo oooo read h (high or low) data o from program memory at word address c : a : b . load program memory page 0100 h 000 xxxx xxxx xx bb bbbb iiii iiii write h (high or low) data i to program memory page at word address b . data low byte must be loaded before data high byte is applied within the same address. write program memory page 0100 1100 aaaa aaaa bb xx xxxx xxxx xxxx write program memory page at address c : a : b . read eeprom memory 1010 0000 0000 aaaa bbbb bbbb oooo oooo read data o from eeprom memory at address a : b . write eeprom memory 1100 0000 0000 aaaa bbbb bbbb iiii iiii write data i to eeprom memory at address a : b . load eeprom memory page (page access) 1100 0001 0000 0000 0000 00 bb iiii iiii load data i to eeprom memory page buffer. after data is loaded, program eeprom page. write eeprom memory page (page access) 1100 0010 0000 aaaa bbbb bb00 xxxx xxxx write eeprom page at address a : b . read lock bits 0101 1000 0000 0000 xxxx xxxx xx oo oooo read lock bits. ?0? = programmed, ?1? = unprogrammed. see table 25-1 on page 246 for details. write lock bits 1010 1100 111x xxxx xxxx xxxx 11 ii iiii write lock bits. set bits = ?0? to program lock bits. see table 25-1 on page 246 for details. read signature byte 0011 0000 000x xxxx xxxx xx bb oooo oooo read signature byte o at address b . write fuse bits 1010 1100 1010 0000 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. write fuse high bits 1010 1100 1010 1000 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. write extended fuse bits 1010 1100 1010 0100 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. see table 25-3 on page 247 for details. read fuse bits 0101 0000 0000 0000 xxxx xxxx oooo oooo read fuse bits. ?0? = programmed, ?1? = unprogrammed. read fuse high bits 0101 1000 0000 1000 xxxx xxxx oooo oooo read fuse high bits. ?0? = pro- grammed, ?1? = unprogrammed.
263 7799d?avr?11/10 atmega8u2/16u2/32u2 note: a = address high bits, b = address low bits, c = address extended bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care 25.9.2 serial programming characteristics for characteristics of the serial programming module see ?spi timing characteristics? on page 269 . read extended fuse bits 0101 0000 0000 1000 xxxx xxxx oooo oooo read extended fuse bits. ?0? = pro- grammed, ?1? = unprogrammed. see table 25-3 on page 247 for details. read calibration byte 0011 1000 000x xxxx 0000 0000 oooo oooo read calibration byte poll rdy/ bsy 1111 0000 0000 0000 xxxx xxxx xxxx xxx o if o = ?1?, a programming operation is still busy. wait until this bit returns to ?0? before applying another command. table 25-16. serial programming instruction set (continued) instruction instruction format operation byte 1 byte 2 byte 3 byte4
264 7799d?avr?11/10 atmega8u2/16u2/32u2 26. electrical characteristics 26.1 absolute maximum ratings* 26.2 dc characteristics operating temperature ................................. -55 ? c to +125 ? c *notice: stresses beyond those listed under ?absolute maximum ratings? may cause permanent dam- age to the device. this is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of this specification is not implied. exposure to absolute maximum rating conditions for extended periods may affect device reliability. storage temperature..................................... -65c to +150c voltage on any pin except reset & uvcc with respect to ground (7) .............................-0.5v to v cc +0.5v voltage on reset with respect to ground .....-0.5v to +13.0v voltage on uvcc with respect to ground...........-0.5v to +6.0v maximum operating voltage ............................................ 6.0v dc current per i/o pin ............................................... 40.0 ma dc current v cc and gnd pins................................ 200.0 ma t a = -40 ? c to 85 ? c, v cc = 2.7v to 5.5v (unless otherwise noted) symbol parameter condition min. (5) typ. max. (5) units v il input low voltage, standard ios (8) v cc = 2.7v - 5.5v -0.5 0.8 v v il1 input low voltage, xtal1 pin v cc = 2.7v - 5.5v -0.5 0.1v cc (1) v v il2 input low voltage, reset pin v cc = 2.7v - 5.5v -0.5 0.1v cc (1) v v ih input high voltage, standard ios (8) v cc = 2.7v - 5.5v 2 v cc + 0.5 v v ih1 input high voltage, xtal1 pin v cc = 2.7v - 5.5v 0.7v cc (2) v cc + 0.5 v v ih2 input high voltage, reset pin v cc = 2.7v - 5.5v 0.9v cc (2) v cc + 0.5 v v ol output low voltage (3) , standard ios (8) , mosi/miso pins i ol = 10ma, v cc = 5v i ol = 5ma, v cc = 3v 0.7 0.5 v v oh output high voltage (4) , standard ios (8) , mosi/miso pins i oh = -10ma, v cc = 5v i oh = -5ma, v cc = 3v 4.2 2.3 v i il input leakage current i/o pin v cc = 5.5v, pin low (absolute value) 1 a i ih input leakage current i/o pin v cc = 5.5v, pin high (absolute value) 1 a r rst reset pull-up resistor 30 60 k ? r pu i/o pin pull-up resistor 20 50 k ?
265 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. "max" means the highest value where the pin is guaranteed to be read as low 2. "min" means the lowest value where the pin is guaranteed to be read as high 3. although each i/o port can sink more than the test conditions (20ma at vcc = 5v, 10ma at vcc = 3v) under steady state conditions (non-transient), the following must be observed: 1.)the sum of all iol, for ports b0-b7, c0-c7, d0-d7 should not exceed 150 ma. if iol exceeds the test condition, vol may exceed the related specification. pins are not guaranteed to sink current greater than the listed test condition. 4. although each i/o port can source more than the test conditions (20ma at vcc = 5v, 10ma at vcc = 3v) under steady state conditions (non-transient), the following must be observed: 1.)the sum of all iol, for ports b0-b7, c0-c7, d0-d7 should not exceed 150 ma. if ioh exceeds the test condition, voh may exceed the related specification. pins are not guaranteed to source current greater than the listed test condition. r pudp usb d+ internal pull-up idle mode 900 1500 ? streaming mode 1425 3090 ? i cc power supply current (6) active 8 mhz, v cc = 3v regulator disabled 46ma active 16 mhz, v cc = 5v regulator enabled 13.5 21 ma idle 8 mhz, v cc = 3v regulator disabled 0.8 1.2 ma idle 16 mhz, v cc = 5v regulator enabled 3.2 4.0 ma power-down mode wdt disabled, regulator disabled,v cc = 3v 510 a wdt enabled, regulator disabled,v cc = 3v 10 15 a wdt, bod, regulator enabled, vcc = 5v 40 65 a standby mode - 8mhz xtal wdt disabled, bod enabled, regulator disabled, vcc = 3v 250 a wdt disabled, bod, regulator enabled, vcc = 5v 350 a v acio analog comparator input offset voltage v cc = 5v v in = v cc /2 <10 40 mv i aclk analog comparator input leakage current v cc = 5v v in = v cc /2 -50 50 na t acid analog comparator propagation delay v cc = 2.7v v cc = 4.0v 750 500 ns rusb usb series resistor (external) 225% ? vreg regulator output voltage vcc 4.0v, i ? 100ma, c ucap =1 f20% 3.0 3.3 3.6 v uvcc 4 5.5 v t a = -40 ? c to 85 ? c, v cc = 2.7v to 5.5v (unless otherwise noted) (continued) symbol parameter condition min. (5) typ. max. (5) units
266 7799d?avr?11/10 atmega8u2/16u2/32u2 5. all dc characteristics contained in this datasheet are based on simulation and characterization of other avr microcon- trollers manufactured in the same process technology. these values are preliminary values representing design targets, and will be updated after characterization of actual silicon 6. values with ?prr1 ? power reduction register 1? disabled (0x00). 7. as specified in the usb electrical chapter, the d+/d- pads can withstand voltages down to -1v applied through a 39 ? resis- tor (in series with the external 39 ? resistor). 8. all ios except xtal1 and reset pins 26.3 speed grades maximum frequency is depending on v cc. as shown in figure 26-1 , the maximum frequency vs. v cc curve is linear between 2.7v < v cc < 4.5v. figure 26-1. maximum frequency vs. v cc , atmega8u2/16u2/32u2 26.4 clock characteristics 26.4.1 calibrated internal rc oscillator accuracy 26.4.2 external clock drive waveforms figure 26-2. external clock drive waveforms 1 6 mhz 8 mhz 2.7v 4.5v 5.5v safe operating area table 26-1. calibration accuracy of internal rc oscillator frequency v cc temperature calibration accuracy factory calibration 8.0 mhz 3v 25 ? c 10% user calibration 7.3 - 8.1 mhz 2.7v - 5.5v -40 ? c - 85 ? c1% v il1 v ih1
267 7799d?avr?11/10 atmega8u2/16u2/32u2 26.4.3 external clock drive note: all dc characteristics contained in this datasheet are based on simulation and characterization of other avr microcontrollers manufactured in the same process technology. these values are pre- liminary values representing design targets, and will be updated after characterization of actual silicon. 26.5 system and reset characteristics note: the por will not work unless the supply voltage has been below vpot (falling) table 26-2. external clock drive symbol parameter v cc =2.7-5.5v v cc =4.5-5.5v units min. max. min. max. 1/t clcl oscillator frequency 0 8 0 16 mhz t clcl clock period 125 62.5 ns t chcx high time 50 25 ns t clcx low time 50 25 ns t clch rise time 1.6 0.5 ? s t chcl fall time 1.6 0.5 ? s ? t clcl change in period from one clock cycle to the next 22% table 26-3. reset, brown-out and internal voltage reference characteristics symbol parameter condition min typ max units v pot power-on reset threshold voltage (rising) 1.4 2.3 v power-on reset threshold voltage (falling) (note:) 1.3 2.3 v v por v cc start voltage to ensure internal power-on reset signal -0.1 0.1 v v ccrr v cc rise rate to ensure internal power_on reset signal 0.3 v/ms t rst minimum pulse width on reset pin 5v, 25c 400 ns v hyst brown-out detector hysteresis 50 mv t bod min pulse width on brown-out reset ns v bg bandgap reference voltage v cc = 2.7v - 5.5v 1.0 1.1 1.2 v t bg bandgap reference start-up time - 40 70 s i bg bandgap reference current consumption - 10 a
268 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. the test is performed using bodlevel = 000 and 110. 26.6 external interrupts characteristics table 26-4. bodlevel fuse coding bodlevel 2..0 fuses min v bot (1) typ v bot max v bot (1) units 111 bod disabled 110 2.5 2.7 2.9 v 101 reserved 100 3.0 011 3.5 010 reserved 001 4.0 000 4.1 4.3 4.5 table 26-5. asynchronous external interrupt characteristics symbol parameter condition min typ max units t int minimum pulse width for asynchronous external interrupt 50 ns
269 7799d?avr?11/10 atmega8u2/16u2/32u2 26.7 spi timing characteristics see figure 26-3 and figure 26-7 for details. note: 1. in spi programming mode the minimum sck high/low period is: - 2 t clcl for f ck < 12 mhz - 3 t clcl for f ck > 12 mhz figure 26-3. spi interface timing requirements (master mode) table 26-6. spi timing parameters description mode min typ max 1 sck period master see table 17-5 ns 2 sck high/low master 50% duty cycle 3 rise/fall time master tbd 4 setup master 10 5 hold master 10 6 out to sck master 0.5 ? t sck 7 sck to out master 10 8 sck to out high master 10 9 ss low to out slave 15 10 sck period slave 4 ? t ck 11 sck high/low (1) slave 2 ? t ck 12 rise/fall time slave tbd 13 setup slave 10 14 hold slave t ck 15 sck to out slave 15 16 sck to ss high slave 20 17 ss high to tri-state slave 10 18 ss low to sck slave 20 mo si (data output) sck (cpol = 1) mi so (data input) sck (cpol = 0) ss msb lsb lsb msb ... ... 61 22 3 45 8 7
270 7799d?avr?11/10 atmega8u2/16u2/32u2 table 26-7. spi interface timing requirements (slave mode) 26.8 hardware boot entrancetiming characteristics figure 26-4. hardware boot timing requirements 26.9 parallel programming characteristics figure 26-5. parallel programming timing, including some general timing requirements mi so (data output) sck (cpol = 1) mo si (data input) sck (cpol = 0) ss msb lsb lsb msb ... ... 10 11 11 12 13 14 17 15 9 x 16 table 26-8. hardware boot timings symbol parameter min max tshrh hwb low setup before reset high 0 thhrh hwb low hold after reset high startuptime(sut) + time out delay(tout) reset ale/hwb t shrh t hhrh data & contol (data, xa0/1, bs1, bs2) xtal1 t xhxl t wlwh t dvxh t xldx t plwl t wlrh wr rdy/bsy pagel t phpl t plbx t bvph t xlwl t wlbx t bvwl wlrl
271 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 26-6. parallel programming timing, loading sequence with timing requirements (1) note: 1. the timing requirements shown in figure 26-5 (i.e., t dvxh , t xhxl , and t xldx ) also apply to load- ing operation. figure 26-7. parallel programming timing, reading sequence (within the same page) with timing requirements (1) note: 1. the timing requirements shown in figure 26-5 (i.e., t dvxh , t xhxl , and t xldx ) also apply to read- ing operation. table 26-9. parallel programming characteristics, v cc = 5v 10% symbol parameter min typ max units v pp programming enable voltage 11.5 12.5 v i pp programming enable current 250 ? a t dvxh data and control valid before xtal1 high 67 ns t xlxh xtal1 low to xtal1 high 200 ns t xhxl xtal1 pulse width high 150 ns t xldx data and control hold after xtal1 low 67 ns xtal1 pagel t plxh xlxh t t xlph addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) load data (low byte) load data (high byte) load data load address (low byte) xtal1 oe addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) read data (low byte) read data (high byte) load address (low byte) t bvdv t oldv t xlol t ohdz
272 7799d?avr?11/10 atmega8u2/16u2/32u2 notes: 1. t wlrh is valid for the write flash, write eeprom, write fuse bits and write lock bits commands. 2. t wlrh_ce is valid for the chip erase command. t xlwl xtal1 low to wr low 0 ns t xlph xtal1 low to pagel high 0 ns t plxh pagel low to xtal1 high 150 ns t bvph bs1 valid before pagel high 67 ns t phpl pagel pulse width high 150 ns t plbx bs1 hold after pagel low 67 ns t wlbx bs2/1 hold after wr low 67 ns t plwl pagel low to wr low 67 ns t bvwl bs2/1 valid to wr low 67 ns t wlwh wr pulse width low 150 ns t wlrl wr low to rdy/ bsy low 0 1 ? s t wlrh wr low to rdy/ bsy high (1) 3.7 4.5 ms t wlrh_ce wr low to rdy/ bsy high for chip erase (2) 7.5 9 ms t xlol xtal1 low to oe low 0 ns t bvdv bs1 valid to data valid 0 250 ns t oldv oe low to data valid 250 ns t ohdz oe high to data tri-stated 250 ns table 26-9. parallel programming characteristics, v cc = 5v 10% (continued) symbol parameter min typ max units
273 7799d?avr?11/10 atmega8u2/16u2/32u2 27. typical characteristics the following charts show typical behavior. these f igures are not tested during manufacturing. all current consumption measurements are performed with all i/o pins configured as inputs and with internal pull-ups enabled. a sine wave generator with rail-to-rail output is used as clock source. all active- and idle current consumption measurements are done with all bits in the prr regis- ters set and thus, the corresponding i/o modules are turned off. also the analog comparator is disabled during these measurements. the power consumption in power-down mode is independent of clock selection. the current consumption is a function of several factors such as: operating voltage, operating frequency, loading of i/o pins, switching rate of i/o pins, code executed and ambient tempera- ture. the dominating factors are operating voltage and frequency. the current drawn from capacitive loaded pins may be estimated (for one pin) as c l * v cc *f where c l = load capacitance, v cc = operating voltage and f = average switching frequency of i/o pin. the parts are characterized at frequencies higher than test limits. parts are not guaranteed to function properly at frequencies higher than the ordering code indicates. the difference between current consumption in power-down mode with watchdog timer enabled and power-down mode with watchdog timer disabled represents the differential cur- rent drawn by the watchdog timer. 27.1 active supply current figure 27-1. active supply current vs. frequency (regulator enabled t = 85c) 5.5 v 5.0 v 4.5 v 4.0 v 0 2 4 6 8 10 12 14 16 18 012345678910111213141516 frequency (mhz) i cc (ma) 3.6 v 2.7 v
274 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 27-2. active supply current vs. frequency ( regulator disabled t = 85c ) 27.2 idle supply current figure 27-3. idle supply current vs. frequency ( regulator enabled t = 85c) 3.6 v 3.3 v 3.0 v 2.7 v 0 1 2 3 4 5 6 7 8 012345678910111213141516 frequency (mhz) i cc (ma) 0 0.5 1 1.5 2 2.5 3 3.5 4 012345678910111213141516 frequency (mhz) i cc (ma) 5.5 v 5.0 v 4.5 v 4.0 v 3.6 v
275 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 27-4. idle supply current vs. frequency ( regulator disabled t = 85c 27.3 power-down supply current figure 27-5. power-down supply current vs. v cc (watchdog timer disabled) 0 0.3 0.6 0.9 1.2 1.5 1.8 2.1 012345678910111213141516 frequency (mhz) i cc (ma) 3.6 v 3.3 v 2.7 v 85 c 25 c 4.4 4.7 5 5.3 5.6 5.9 6.2 6.5 6.8 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc (v) i cc (ua)
276 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 27-6. power-down supply current vs. v cc (watchdog timer enabled) figure 27-7. power-down supply current vs. v cc (wdt enabled boden) 85 c 25 c 8 9 10 11 12 13 14 15 16 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc (v) i cc (ua) 85 c 25 c 31 33 35 37 39 41 43 3.5 3.7 3.9 4.1 4.3 4.5 4.7 4.9 5.1 5.3 5.5 v cc (v) i cc (ua)
277 7799d?avr?11/10 atmega8u2/16u2/32u2 27.4 pin pull-up figure 27-8. i/o pin pull-up resistor current vs. input voltage (v cc = 5 v) figure 27-9. reset pull-up resistor current vs. reset pin voltage (v cc = 5 v) 85 c 25 c -40 c 0 25 50 75 100 125 150 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 v op (v) i op (ua) 85 c 25 c -40 c 0 20 40 60 80 100 120 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 v reset (v) i reset (ua)
278 7799d?avr?11/10 atmega8u2/16u2/32u2 27.5 pin driver strength figure 27-10. i/o pin output voltage vs. sink current(v cc = 3 v) figure 27-11. i/o pin output voltage vs. sink current(v cc = 5 v) 85 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 3.5 4 02468101214161820 i ol (ma) v ol (v) 85 c 25 c -40 c 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 02468101214161820 i ol (ma) v ol (v)
279 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 27-12. i/o pin output voltage vs. source current(vcc = 3 v) figure 27-13. i/o pin output voltage vs. source current(v cc = 5 v) 25 c -40 c 0 0.5 1 1.5 2 2.5 3 3.5 02468101214161820 i oh (ma) v oh (v) 85 c 85 c 25 c -40 c 4 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 5 0 2 4 6 8 10 12 14 16 18 20 i oh (ma) v oh (v)
280 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 27-14. usb dp hi pull-up resistor current vs. usb pin voltage 27.6 pin threshold and hysteresis figure 27-15. i/o pin input threshold voltage vs. v cc (v ih , i/o pin read as ?1?) 85 c 25 c -40 c 0 200 400 600 800 1000 1200 1400 1600 0 0.5 1 1.5 2 2.5 3 3.5 v usb (v) i usb (ua) 85 c 25 c -40 c 0.7 0.9 1.1 1.3 1.5 1.7 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc (v) threshold (v)
281 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 27-16. i/o pin input threshold voltage vs. v cc (v il , i/o pin read as ?0?) 27.7 bod threshold figure 27-17. bod thresholds vs. temperature (bodlevel is 2.7 v) 85 c 25 c -40 c 0.6 0.8 1 1.2 1.4 1.6 1.8 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9 5.2 5.5 v cc (v) threshold (v) rising vcc falling vcc 2.71 2.72 2.73 2.74 2.75 2.76 2.77 2.78 2.79 2.8 2.81 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 temperature (c) threshold (v)
282 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 27-18. bod thresholds vs. temperature (bodlevel is 3.5 v) figure 27-19. bod thresholds vs. temperature (bodlevel is 4.3 v) rising vcc falling vcc 3.51 3.52 3.53 3.54 3.55 3.56 3.57 3.58 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 temperature (c) threshold (v) 4.31 4.32 4.33 4.34 4.35 4.36 4.37 4.38 4.39 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 temperature (c) threshold (v) falling vcc rising vcc
283 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 27-20. bandgap voltage vs. vcc 27.8 internal oscilllator speed figure 27-21. watchdog oscillator frequency vs. temperature 1.095 1.097 1.099 1.101 1.103 1.105 1.107 2.5 3 3.5 4 4.5 5 5.5 vcc (v) bandgap voltage (v) 85 c 25 c -40 c 5.5 v 3.6 v 2.7 v 1.9 v 110 111 112 113 114 115 116 117 118 119 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 temperature (c) f rc (khz)
284 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 27-22. watchdog oscillator frequency vs. v cc figure 27-23. calibrated 8 mhz rc oscillator frequency vs. v cc 85 c 25 c -40 c 109 110 111 112 113 114 115 116 117 118 119 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (khz) 85 c 25 c -40 c 7.7 7.8 7.9 8 8.1 8.2 8.3 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (mhz)
285 7799d?avr?11/10 atmega8u2/16u2/32u2 figure 27-24. calibrated 8 mhz rc oscillator frequency vs. temperature figure 27-25. calibrated 8 mhz rc oscillator frequency vs. osccal value 5.5 v 4.5 v 3.3 v 2.7 v 7.7 7.8 7.9 8 8.1 8.2 8.3 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 temperature (c) f rc (mhz) 85 c 25 c -40 c 0 2 4 6 8 10 12 14 16 0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256 osccal (x1) f rc (mhz)
286 7799d?avr?11/10 atmega8u2/16u2/32u2 27.9 current consumption of peripheral units figure 27-26. usb regulator level vs. v cc figure 27-27. usb regulator level with load 75 ? vs. v cc 85 c 25 c -40 c 2.8 2.9 3 3.1 3.2 3.3 3.4 33.544.555.5 input voltage (v) output voltage (v) 85 c 25 c -40 c 2.2 2.4 2.6 2.8 3 3.2 3.4 2.5 3 3.5 4 4.5 5 5.5 voltage (v) voltage (v)
287 7799d?avr?11/10 atmega8u2/16u2/32u2 27.10 current consumption in reset and reset pulsewidth figure 27-28. reset supply current vs. frequency (excluding current through the reset pullup) 5.5 v 5.0 v 4.5 v 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 012345678910111213141516 frequency (mhz) i cc (ma) 3.6 v
288 7799d?avr?11/10 atmega8u2/16u2/32u2 28. register summary address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page (0xff) reserved - - - - - - - - (0xfe) reserved - - - - - - - - (0xfd) reserved - - - - - - - - (0xfc) reserved - - - - - - - - (0xfb) upoe upwe1 upwe0 updrv1 updrv0 scki datai dpi dmi page 195 (0xfa) reserved - - - - - - - - (0xf9) reserved - - - - - - - - (0xf8) reserved - - - - - - - - (0xf7) reserved - - - - - - - - (0xf6) reserved - - - - - - - - (0xf5) reserved - - - - - - - - (0xf4) ueint - - epint4:0 page 222 (0xf3) reserved - - - - - - - - (0xf2) uebclx byct7:0 page 221 (0xf1) uedatx dat7:0 page 221 (0xf0) ueienx flerre nakine - nakoute rxstpe rxoute stallede txine page 220 (0xef) uesta1x - - - - - ctrldir currbk1:0 page 218 (0xee) uesta0x cfgok overfi underfi - dtseq1:0 nbusybk1:0 page 217 (0xed) uecfg1x - epsize2:0 epbk1:0 alloc - page 216 (0xec) uecfg0x eptype1:0 - - - - - epdir page 215 (0xeb) ueconx - - stallrq stallrqc rstdt - - epen page 214 (0xea) uerst - - - eprst4:0 page 214 (0xe9) uenum - - - - - epnum2:0 page 214 (0xe8) ueintx fifocon nakini rwal nakouti rxstpi rxouti stalledi txini page 219 (0xe7) reserved - - - - - - - - (0xe6) udmfn - - - fncerr - - - - page 213 (0xe5) udfnumh - - - - - fnum10:8 page 213 (0xe4) udfnuml fnum7:0 page 213 (0xe3) udaddr adden uadd6:0 page 212 (0xe2) udien - uprsme eorsme wakeupe eorste sofe - suspe page 211 (0xe1) udint - uprsmi eorsmi wakeupi eorsti sofi - suspi page 210 (0xe0) udcon - - - rputx - rstcpu rmwkup detach page 209 (0xdf) reserved - - - - - - - - (0xde) reserved - - - - - - - - (0xdd) reserved - - - - - - - - (0xdc) reserved - - - - - - - - (0xdb) reserved - - - - - - - - (0xda) reserved - - - - - - - - (0xd9) reserved - - - - - - - - (0xd8) usbcon usbe - frzclk - - - - - page 195 (0xd7) reserved - - - - - - - - (0xd6) reserved - - - - - - - - (0xd5) reserved - - - - - - - - (0xd4) reserved - - - - - - - - (0xd3) reserved - - - - - - - - (0xd2) clksta - - - - - - rcon exton page 38 (0xd1) clksel1 rccksel3 rccksel2 rccksel1 rccksel0 excksel3 excksel2 excksel1 excksel0 page 38 (0xd0) clksel0 rcsut1 rcsut0 exsut1 exsut0 rce exte - clks page 37 (0xcf) reserved - - - - - - - - (0xce) udr1 usart1 i/o data register page 167 (0xcd) ubrr1h - - - - usart1 baud rate register high byte page 171 (0xcc) ubrr1l usart1 baud rate register low byte page 171 (0xcb) ucsr1d - - - - - - ctsen rtsen page 171 (0xca) ucsr1c umsel11 umsel10 upm11 upm10 usbs1 ucsz11 ucsz10 ucpol1 page 169 (0xc9) ucsr1b rxcie1 txcie1 udrie1 rxen1 txen1 ucsz12 rxb81 txb81 page 168 (0xc8) ucsr1a rxc1 txc1 udre1 fe1 dor1 pe1 u2x1 mpcm1 page 167 (0xc7) reserved - - - - - - - - (0xc6) reserved - - - - - - - - (0xc5) reserved - - - - - - - - (0xc4) reserved - - - - - - - - (0xc3) reserved - - - - - - - - (0xc2) reserved - - - - - - - - (0xc1) reserved - - - - - - - - (0xc0) reserved - - - - - - - - (0xbf) reserved - - - - - - - -
289 7799d?avr?11/10 atmega8u2/16u2/32u2 (0xbe) reserved - - - - - - - - (0xbd) reserved - - - - - - - - (0xbc) reserved - - - - - - - - (0xbb) reserved - - - - - - - - (0xba) reserved - - - - - - - - (0xb9) reserved - - - - - - - - (0xb8) reserved - - - - - - - - (0xb7) reserved - - - - - - - - (0xb6) reserved - - - - - - - - (0xb5) reserved - - - - - - - - (0xb4) reserved - - - - - - - - (0xb3) reserved - - - - - - - - (0xb2) reserved - - - - - - - - (0xb1) reserved - - - - - - - - (0xb0) reserved - - - - - - - - (0xaf) reserved - - - - - - - - (0xae) reserved - - - - - - - - (0xad) reserved - - - - - - - - (0xac) reserved - - - - - - - - (0xab) reserved - - - - - - - - (0xaa) reserved - - - - - - - - (0xa9) reserved - - - - - - - - (0xa8) reserved - - - - - - - - (0xa7) reserved - - - - - - - - (0xa6) reserved - - - - - - - - (0xa5) reserved - - - - - - - - (0xa4) reserved - - - - - - - - (0xa3) reserved - - - - - - - - (0xa2) reserved - - - - - - - - (0xa1) reserved - - - - - - - - (0xa0) reserved - - - - - - - - (0x9f) reserved - - - - - - - - (0x9e) reserved - - - - - - - - (0x9d) reserved - - - - - - - - (0x9c) reserved - - - - - - - - (0x9b) reserved - - - - - - - - (0x9a) reserved - - - - - - - - (0x99) reserved - - - - - - - - (0x98) reserved - - - - - - - - (0x97) reserved - - - - - - - - (0x96) reserved - - - - - - - - (0x95) reserved - - - - - - - - (0x94) reserved - - - - - - - - (0x93) reserved - - - - - - - - (0x92) reserved - - - - - - - - (0x91) reserved - - - - - - - - (0x90) reserved - - - - - - - - (0x8f) reserved - - - - - - - - (0x8e) reserved - - - - - - - - (0x8d) ocr1ch timer/counter1 - output compare register c high byte page 135 (0x8c) ocr1cl timer/counter1 - output compare register c low byte page 135 (0x8b) ocr1bh timer/counter1 - output compare register b high byte page 135 (0x8a) ocr1bl timer/counter1 - output compare register b low byte page 135 (0x89) ocr1ah timer/counter1 - output compare register a high byte page 135 (0x88) ocr1al timer/counter1 - output compare register a low byte page 135 (0x87) icr1h timer/counter1 - input capture register high byte page 135 (0x86) icr1l timer/counter1 - input capture register low byte page 135 (0x85) tcnt1h timer/counter1 - counter register high byte page 134 (0x84) tcnt1l timer/counter1 - counter register low byte page 134 (0x83) reserved - - - - - - - - (0x82) tccr1c foc1a foc1b foc1c - - - - - page 134 (0x81) tccr1b icnc1 ices1 - wgm13 wgm12 cs12 cs11 cs10 page 133 (0x80) tccr1a com1a1 com1a0 com1b1 com1b0 com1c1 com1c0 wgm11 wgm10 page 129 (0x7f) didr1 - ain6d ain5d ain4d ain3d ain2d ain1d ain0d page 225 (0x7e) reserved - - - - - - - - (0x7d) acmux - - - - - cmux2 cmux1 cmux0 page 225 address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
290 7799d?avr?11/10 atmega8u2/16u2/32u2 (0x7c) reserved - - - - - - - - (0x7b) reserved - - - - - - - - (0x7a) reserved - - - - - - - - (0x79) reserved - - - - - - - - (0x78) reserved - - - - - - - - (0x77) reserved - - - - - - - - (0x76) reserved - - - - - - - - (0x75) reserved - - - - - - - - (0x74) reserved - - - - - - - - (0x73) reserved - - - - - - - - (0x72) reserved - - - - - - - - (0x71) reserved - - - - - - - - (0x70) reserved - - - - - - - - (0x6f) timsk1 - - icie1 - ocie1c ocie1b ocie1a toie1 page 135 (0x6e) timsk0 - - - - - ocie0b ocie0a toie0 page 106 (0x6d) reserved - - - - - - - - (0x6c) pcmsk1 - - - pcint12 pcint11 pcint10 pcint9 pcint8 page 87 (0x6b) pcmsk0 pcint7 pcint6 pcint5 pcint4 pcint3 pcint2 pcint1 pcint0 page 87 (0x6a) eicrb isc71 isc70 isc61 isc60 isc51 isc50 isc41 isc40 page 85 (0x69) eicra isc31 isc30 isc21 isc20 isc11 isc10 isc01 isc00 page 84 (0x68) pcicr - - - - - - pcie1 pcie0 page 86 (0x67) reserved - - - - - - - - (0x66) osccal oscillator calibration register page 38 (0x65) prr1 prusb - - - - - - prusart1 page 46 (0x64) prr0 - - prtim0 - prtim1 prspi - - page 46 (0x63) regcr - - - - - - - regdis page 196 (0x62) wdtckd - - wdewifcm wclkd2 wdewif wdewie wclkd1 wclkd0 page 57 (0x61) clkpr clkpce - - - clkps3 clkps2 clkps1 clkps0 page 39 (0x60) wdtcsr wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 page 56 0x3f (0x5f) sreg i t h s v n z c page 9 0x3e (0x5e) sph sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 page 12 0x3d (0x5d) spl sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 page 12 0x3c (0x5c) reserved - - - - - - - - 0x3b (0x5b) reserved - - - - - - - - 0x3a (0x5a) reserved - - - - - - - - 0x39 (0x59) reserved - - - - - - - - 0x38 (0x58) reserved - - - - - - - - 0x37 (0x57) spmcsr spmie rwwsb sigrd rwwsre blbset pgwrt pgers spmen page 242 0x36 (0x56) reserved - - - - - - - - 0x35 (0x55) mcucr - - - - - - ivsel ivce page 65 , 82 0x34 (0x54) mcusr - - usbrf - wdrf borf extrf porf page 55 0x33 (0x53) smcr - - - - sm2 sm1 sm0 se page 45 0x32 (0x52) reserved - - - - - - - - 0x31 (0x51) dwdr debugwire data register page 245 0x30 (0x50) acsr acd acbg aco aci acie acic acis1 acis0 page 224 0x2f (0x4f) reserved - - - - - - - - 0x2e (0x4e) spdr spi data register page 147 0x2d (0x4d) spsr spif wcol - - - - - spi2x page 146 0x2c (0x4c) spcr spie spe dord mstr cpol cpha spr1 spr0 page 145 0x2b (0x4b) gpior2 general purpose i/o register 2 page 24 0x2a (0x4a) gpior1 general purpose i/o register 1 page 24 0x29 (0x49) pllcsr - - - pllp2 pllp1 pllp0 plle plock page 40 0x28 (0x48) ocr0b timer/counter0 output compare register b page 106 0x27 (0x47) ocr0a timer/counter0 output compare register a page 106 0x26 (0x46) tcnt0 timer/counter0 (8 bit) page 106 0x25 (0x45) tccr0b foc0a foc0b - - wgm02 cs02 cs01 cs00 page 105 0x24 (0x44) tccr0a com0a1 com0a0 com0b1 com0b0 - - wgm01 wgm00 page 105 0x23 (0x43) gtccr tsm - - - - - psrasy psrsync page 89 0x22 (0x42) eearh - - - - eeprom address register high byte page 20 0x21 (0x41) eearl eeprom address register low byte page 20 0x20 (0x40) eedr eeprom data register page 20 0x1f (0x3f) eecr - - eepm1 eepm0 eerie eempe eepe eere page 21 0x1e (0x3e) gpior0 general purpose i/o register 0 page 25 0x1d (0x3d) eimsk int7 int6 int5 int4 int3 int2 int1 int0 page 86 0x1c (0x3c) eifr intf7 intf6 intf5 intf4 intf3 intf2 intf1 intf0 page 86 0x1b (0x3b) pcifr - - - - - - pcif1 pcif0 page 86 address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
291 7799d?avr?11/10 atmega8u2/16u2/32u2 note: 1. for compatibility with future devices, reserved bits should be written to zero if accessed. moreover reserved bits are n ot guaranteed to be read as ?0?. reserved i/o memory addresses should never be written. 2. i/o registers within the address range $00 - $1f are directly bit-accessible using the sbi and cbi instructions. in these reg - isters, the value of single bits can be checked by using the sbis and sbic instructions. 3. some of the status flags are cleared by writing a logical one to them. note that the cbi and sbi instructions will operate on all bits in the i/o register, writing a one back into any flag read as set, thus clearing the flag. the cbi and sbi instruction s work with registers 0x00 to 0x1f only. 4. when using the i/o specific commands in and out, the i/o addresses $00 - $3f must be used. when addressing i/o reg- isters as data space using ld and st instructions, $20 must be added to these addresses. the atmega8u2/16u2/32u2 is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from $60 - $1ff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. 0x1a (0x3a) reserved - - - - - - - - 0x19 (0x39) reserved - - - - - - - - 0x18 (0x38) reserved - - - - - - - - 0x17 (0x37) reserved - - - - - - - - 0x16 (0x36) tifr1 - - icf1 - ocf1c ocf1b ocf1a tov1 page 136 0x15 (0x35) tifr0 - - - - - ocf0b ocf0a tov0 page 107 0x14 (0x34) reserved - - - - - - - - 0x13 (0x33) reserved - - - - - - - - 0x12 (0x32) reserved - - - - - - - - 0x11 (0x31) reserved - - - - - - - - 0x10 (0x30) reserved - - - - - - - - 0x0f (0x2f) reserved - - - - - - - - 0x0e (0x2e) reserved - - - - - - - - 0x0d (0x2d) reserved - - - - - - - - 0x0c (0x2c) reserved - - - - - - - - 0x0b (0x2b) portd portd7 portd6 portd5 portd4 portd3 portd2 portd1 portd0 page 83 0x0a (0x2a) ddrd ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 page 83 0x09 (0x29) pind pind7 pind6 pind5 pind4 pind3 pind2 pind1 pind0 page 83 0x08 (0x28) portc portc7 portc6 portc5 portc4 - portc2 portc1 portc0 page 82 0x07 (0x27) ddrc ddc7 ddc6 ddc5 ddc4 - ddc2 ddc1 ddc0 page 82 0x06 (0x26) pinc pinc7 pinc6 pinc5 pinc4 - pinc2 pinc1 pinc0 page 82 0x05 (0x25) portb portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 page 82 0x04 (0x24) ddrb ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 page 82 0x03 (0x23) pinb pinb7 pinb6 pinb5 pinb4 pinb3 pinb2 pinb1 pinb0 page 82 0x02 (0x22) reserved - - - - - - - - 0x01 (0x21) reserved - - - - - - - - 0x00 (0x20) reserved - - - - - - - - address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
292 7799d?avr?11/10 atmega8u2/16u2/32u2 29. instruction set summary mnemonics operands description operation flags #clocks arithmetic and logic instructions add rd, rr add two registers rd ? rd + rr z,c,n,v,h 1 adc rd, rr add with carry two registers rd ? rd + rr + c z,c,n,v,h 1 adiw rdl,k add immediate to word rdh:rdl ? rdh:rdl + k z,c,n,v,s 2 sub rd, rr subtract two registers rd ? rd - rr z,c,n,v,h 1 subi rd, k subtract constant from register rd ? rd - k z,c,n,v,h 1 sbc rd, rr subtract with carry two registers rd ? rd - rr - c z,c,n,v,h 1 sbci rd, k subtract with carry constant from reg. rd ? rd - k - c z,c,n,v,h 1 sbiw rdl,k subtract immediate from word rdh:rdl ? rdh:rdl - k z,c,n,v,s 2 and rd, rr logical and registers rd ?? rd ? rr z,n,v 1 andi rd, k logical and register and constant rd ? rd ?? k z,n,v 1 or rd, rr logical or registers rd ? rd v rr z,n,v 1 ori rd, k logical or register and constant rd ?? rd v k z,n,v 1 eor rd, rr exclusive or registers rd ? rd ? rr z,n,v 1 com rd one?s complement rd ? 0xff ? rd z,c,n,v 1 neg rd two?s complement rd ? 0x00 ? rd z,c,n,v,h 1 sbr rd,k set bit(s) in register rd ? rd v k z,n,v 1 cbr rd,k clear bit(s) in register rd ? rd ? (0xff - k) z,n,v 1 inc rd increment rd ? rd + 1 z,n,v 1 dec rd decrement rd ? rd ? 1 z,n,v 1 tst rd test for zero or minus rd ? rd ? rd z,n,v 1 clr rd clear register rd ? rd ? rd z,n,v 1 ser rd set register rd ? 0xff none 1 branch instructions rjmp k relative jump pc ?? pc + k + 1 none 2 ijmp indirect jump to (z) pc ? z none 2 jmp k direct jump pc ?? k none 3 rcall k relative subroutine call pc ? pc + k + 1 none 4 icall indirect call to (z) pc ? z none 4 call k direct subroutine call pc ? k none 5 ret subroutine return pc ? stack none 5 reti interrupt return pc ? stack i 5 cpse rd,rr compare, skip if equal if (rd = rr) pc ?? pc + 2 or 3 none 1/2/3 cp rd,rr compare rd ? rr z, n,v,c,h 1 cpc rd,rr compare with carry rd ? rr ? c z, n,v,c,h 1 cpi rd,k compare register with immediate rd ? k z, n,v,c,h 1 sbrc rr, b skip if bit in register cleared if (rr(b)=0) pc ? pc + 2 or 3 none 1/2/3 sbrs rr, b skip if bit in register is set if (rr(b)=1) pc ? pc + 2 or 3 none 1/2/3 sbic p, b skip if bit in i/o register cleared if (p(b)=0) pc ? pc + 2 or 3 none 1/2/3 sbis p, b skip if bit in i/o register is set if (p(b)=1) pc ? pc + 2 or 3 none 1/2/3 brbs s, k branch if status flag set if (sreg(s) = 1) then pc ? pc+k + 1 none 1/2 brbc s, k branch if status flag cleared if (sreg(s) = 0) then pc ? pc+k + 1 none 1/2 breq k branch if equal if (z = 1) then pc ? pc + k + 1 none 1/2 brne k branch if not equal if (z = 0) then pc ? pc + k + 1 none 1/2 brcs k branch if carry set if (c = 1) then pc ? pc + k + 1 none 1/2 brcc k branch if carry cleared if (c = 0) then pc ? pc + k + 1 none 1/2 brsh k branch if same or higher if (c = 0) then pc ? pc + k + 1 none 1/2 brlo k branch if lower if (c = 1) then pc ? pc + k + 1 none 1/2 brmi k branch if minus if (n = 1) then pc ? pc + k + 1 none 1/2 brpl k branch if plus if (n = 0) then pc ? pc + k + 1 none 1/2 brge k branch if greater or equal, signed if (n ? v= 0) then pc ? pc + k + 1 none 1/2 brlt k branch if less than zero, signed if (n ? v= 1) then pc ? pc + k + 1 none 1/2 brhs k branch if half carry flag set if (h = 1) then pc ? pc + k + 1 none 1/2 brhc k branch if half carry flag cleared if (h = 0) then pc ? pc + k + 1 none 1/2 brts k branch if t flag set if (t = 1) then pc ? pc + k + 1 none 1/2 brtc k branch if t flag cleared if (t = 0) then pc ? pc + k + 1 none 1/2 brvs k branch if overflow flag is set if (v = 1) then pc ? pc + k + 1 none 1/2 brvc k branch if overflow flag is cleared if (v = 0) then pc ? pc + k + 1 none 1/2 brie k branch if interrupt enabled if ( i = 1) then pc ? pc + k + 1 none 1/2 brid k branch if interrupt disabled if ( i = 0) then pc ? pc + k + 1 none 1/2 bit and bit-test instructions sbi p,b set bit in i/o register i/o(p,b) ? 1 none 2 cbi p,b clear bit in i/o register i/o(p,b) ? 0 none 2 lsl rd logical shift left rd(n+1) ? rd(n), rd(0) ? 0 z,c,n,v 1 lsr rd logical shift right rd(n) ? rd(n+1), rd(7) ? 0 z,c,n,v 1
293 7799d?avr?11/10 atmega8u2/16u2/32u2 rol rd rotate left through carry rd(0) ? c,rd(n+1) ? rd(n),c ? rd(7) z,c,n,v 1 ror rd rotate right through carry rd(7) ? c,rd(n) ? rd(n+1),c ? rd(0) z,c,n,v 1 asr rd arithmetic shift right rd(n) ? rd(n+1), n=0..6 z,c,n,v 1 swap rd swap nibbles rd(3..0) ? rd(7..4),rd(7..4) ? rd(3..0) none 1 bset s flag set sreg(s) ? 1 sreg(s) 1 bclr s flag clear sreg(s) ? 0 sreg(s) 1 bst rr, b bit store from register to t t ? rr(b) t 1 bld rd, b bit load from t to register rd(b) ? t none 1 sec set carry c ? 1c1 clc clear carry c ? 0 c 1 sen set negative flag n ? 1n1 cln clear negative flag n ? 0 n 1 sez set zero flag z ? 1z1 clz clear zero flag z ? 0 z 1 sei global interrupt enable i ? 1i1 cli global interrupt disable i ?? 0 i 1 ses set signed test flag s ? 1s1 cls clear signed test flag s ? 0 s 1 sev set twos complement overflow. v ? 1v1 clv clear twos complement overflow v ? 0 v 1 set set t in sreg t ? 1t1 clt clear t in sreg t ? 0 t 1 seh set half carry flag in sreg h ? 1h1 clh clear half carry flag in sreg h ? 0 h 1 data transfer instructions mov rd, rr move between registers rd ? rr none 1 movw rd, rr copy register word rd+1:rd ? rr+1:rr none 1 ldi rd, k load immediate rd ? k none 1 ld rd, x load indirect rd ? (x) none 2 ld rd, x+ load indirect and post-inc. rd ? (x), x ? x + 1 none 2 ld rd, - x load indirect and pre-dec. x ? x - 1, rd ? (x) none 2 ld rd, y load indirect rd ? (y) none 2 ld rd, y+ load indirect and post-inc. rd ? (y), y ? y + 1 none 2 ld rd, - y load indirect and pre-dec. y ? y - 1, rd ? (y) none 2 ldd rd,y+q load indirect with displacement rd ? (y + q) none 2 ld rd, z load indirect rd ? (z) none 2 ld rd, z+ load indirect and post-inc. rd ? (z), z ? z+1 none 2 ld rd, -z load indirect and pre-dec. z ? z - 1, rd ? (z) none 2 ldd rd, z+q load indirect with displacement rd ? (z + q) none 2 lds rd, k load direct from sram rd ? (k) none 2 st x, rr store indirect (x) ?? rr none 2 st x+, rr store indirect and post-inc. (x) ?? rr, x ? x + 1 none 2 st - x, rr store indirect and pre-dec. x ? x - 1, (x) ? rr none 2 st y, rr store indirect (y) ? rr none 2 st y+, rr store indirect and post-inc. (y) ? rr, y ? y + 1 none 2 st - y, rr store indirect and pre-dec. y ? y - 1, (y) ? rr none 2 std y+q,rr store indirect with displacement (y + q) ? rr none 2 st z, rr store indirect (z) ? rr none 2 st z+, rr store indirect and post-inc. (z) ? rr, z ? z + 1 none 2 st -z, rr store indirect and pre-dec. z ? z - 1, (z) ? rr none 2 std z+q,rr store indirect with displacement (z + q) ? rr none 2 sts k, rr store direct to sram (k) ? rr none 2 lpm load program memory r0 ? (z) none 3 lpm rd, z load program memory rd ? (z) none 3 lpm rd, z+ load program memory and post-inc rd ? (z), z ? z+1 none 3 spm store program memory (z) ? r1:r0 none - in rd, p in port rd ? p none 1 out p, rr out port p ? rr none 1 push rr push register on stack stack ? rr none 2 pop rd pop register from stack rd ? stack none 2 mcu control instructions nop no operation none 1 sleep sleep (see specific descr. for sleep function) none 1 wdr watchdog reset (see specific descr. for wdr/timer) none 1 break break for on-chip debug only none n/a mnemonics operands description operation flags #clocks
294 7799d?avr?11/10 atmega8u2/16u2/32u2 30. ordering information 30.1 atmega8u2 speed power supply ordering code package operational range 16 mhz 2.7 - 5.5v atmega8u2-au 32a -40 ? c to +85 ? c atmega8u2-mu 32m1-a package type 32a 32-lead, 7 x7 x 1.2 mm, lead pitch 0.8 mm thin quad flat package 32m1 32-pad, 5 x 5 x 1 mm body, pad pitch 0.50 mm quad flat no lead (qfn)
295 7799d?avr?11/10 atmega8u2/16u2/32u2 30.2 atmega16u2 speed power supply ordering code package operational range 16 mhz 2.7 - 5.5v atmega16u2-au 32a -40 ? c to +85 ? c atmega16u2-mu 32m1-a package type 32a 32-lead, 7 x7 x 1.2 mm, lead pitch 0.8 mm thin quad flat package 32m1 32-pad, 5 x 5 x 1 mm body, pad pitch 0.50 mm quad flat no lead (qfn)
296 7799d?avr?11/10 atmega8u2/16u2/32u2 30.3 atmega32u2 speed power supply ordering code package operational range 16 mhz 2.7 - 5.5v atmega32u2-au 32a -40 ? c to +85 ? c atmega32u2-mu 32m1-a package type 32a 32-lead, 7 x7 x 1.2 mm, lead pitch 0.8 mm thin quad flat package 32m1 32-pad, 5 x 5 x 1 mm body, pad pitch 0.50 mm quad flat no lead (qfn)
297 7799d?avr?11/10 atmega8u2/16u2/32u2 31. packaging information 31.1 qfn32
298 7799d?avr?11/10 atmega8u2/16u2/32u2 31.2 tqfp32
299 7799e?avr?09/2012 atmega8u2/16u2/32u2 32. errata 32.1 errata atmega8u2 the revision letter in this section refers to the revision of the atmega8u2 device. 32.1.1 rev. a and rev b ? full swing oscillator 1. full swing oscillator the maximum frequency for the full swing crystal oscillator is 8mhz. for crystal frequen- cies > 8mhz the full swing crystal oscillator is not guaranteed to operate correctly. problem fix/workaround if a crystal with frequency > 8mhz is used, the low power crystal oscillator option should be used instead. see table 8-1 for an overview of the device clocking options. note that the low power crystal oscillator will not provide full rail-to-rail swing on the xtal2 pin. if sys- tem clock output is needed to drive other clock inputs while running from the low power crystal oscillator, the system clock can be output on portc7 by programming the ckout fuse. 32.2 errata atmega16u2 the revision letter in this section refers to the revision of the atmega16u2 device. 32.2.1 rev. a and rev b ? full swing oscillator 1. full swing oscillator the maximum frequency for the full swing crystal oscillator is 8mhz. for crystal frequen- cies > 8mhz the full swing crystal oscillator is not guaranteed to operate correctly. problem fix/workaround if a crystal with frequency > 8mhz is used, the low power crystal oscillator option should be used instead. see table 8-1 for an overview of the device clocking options. note that the low power crystal oscillator will not provide full rail-to-rail swing on the xtal2 pin. if sys- tem clock output is needed to drive other clock inputs while running from the low power crystal oscillator, the system clock can be output on portc7 by programming the ckout fuse. 32.3 errata atmega32u2 the revision letter in this section refers to the revision of the atmega32u2 device. 32.3.1 rev. c no known errata
300 7799e?avr?09/2012 atmega8u2/16u2/32u2 32.3.2 rev. a and rev b ? full swing oscillator 1. full swing oscillator the maximum frequency for the full swing crystal oscillator is 8mhz. for crystal frequen- cies > 8mhz the full swing crystal oscillator is not guaranteed to operate correctly. problem fix/workaround if a crystal with frequency > 8mhz is used, the low power crystal oscillator option should be used instead. see table 8-1 for an overview of the device clocking options. note that the low power crystal oscillator will not provide full rail-to-rail swing on the xtal2 pin. if sys- tem clock output is needed to drive other clock inputs while running from the low power crystal oscillator, the system clock can be output on portc7 by programming the ckout fuse.
301 7799e?avr?09/2012 atmega8u2/16u2/32u2 33. datasheet revision history please note that the referring page numbers in this section are referred to this document. the referring revision in this section are referring to the document revision. 33.1 rev.7799e ? 09/12 33.2 rev. 7799d ? 11/10 33.3 rev. 7799c ? 12/09 33.4 rev. 7799b ? 06/09 1. renamed package name in figure 1-1 on page 2 from vqfp32 to tqfp32. 2. corrected typos. 1. updated the footnote on page 2. removed the vqfp from the footnote 2. updated section 20-4 ?typical bus powered application with 3.3v i/o? on page 187 . 3. updated figure 20-6 on page 188 . by connecting uvcc to 3v power-supply. 4. updated table 21-2 on page 215 . 10: bulk type, and 01: isochronous type 5. added uvcc limits in electrical characteristics 6. updated ?electrical characteristics? on page 264 . added usb d+ internal pull-up (streaming mode) 7. updated ?register summary? on page 288 . added didr1 (adress: 0x7f) 8. removed figure 27-26: usb regulator consumption with load 75 ? vs. vcc 1. updated ?features? on page 1 . 2. added description of ?avcc? on page 4 . 3. updated figure 7-2 on page 18 . 4. updated figure 20-3 on page 186 and figure 20-4 on page 187 . 5. updated ?fuse bits? on page 247 . 6. updated ?dc characteristics? on page 264 . 7. updated table 26-3 on page 267 , by removing vrst. 8. updated table 26-4 on page 268 . 9. updated ?typical characteristics? on page 273 . 10. added new ?errata? on page 299 . 1. updated ?typical characteristics? on page 273 .
302 7799e?avr?09/2012 atmega8u2/16u2/32u2 33.5 rev. 7799a ? 03/09 1. initial revision.
i 7799d?avr?11/10 atmega8u2/16u2/32u2 table of contents features ..................................................................................................... 1 1 pin configurations ................................................................................... 2 1.1disclaimer ................................................................................................................. .2 2 overview ................................................................................................... 3 2.1block diagram ...........................................................................................................3 2.2pin descriptions .........................................................................................................4 3 resources ................................................................................................. 6 4 code examples ........................................................................................ 6 5 data retention .......................................................................................... 6 6 avr cpu core .......................................................................................... 7 6.1introduction ............................................................................................................... .7 6.2architectural overview ...............................................................................................7 6.3alu ? arithmetic logic unit .......................................................................................8 6.4status register ..........................................................................................................8 6.5general purpose register file ................................................................................10 6.6stack pointer ...........................................................................................................11 6.7instruction execution timing ...................................................................................12 6.8reset and interrupt handling ...................................................................................13 7 avr memories ........................................................................................ 16 7.1in-system reprogrammable flash program memory .............................................16 7.2sram data memory ................................................................................................17 7.3eeprom data memory ..........................................................................................18 7.4i/o memory ..............................................................................................................19 7.5register description ................................................................................................20 8 system clock and clock options ......................................................... 26 8.1clock systems and their distribution .......................................................................26 8.2clock switch ............................................................................................................27 8.3clock sources .........................................................................................................29 8.4low power crystal oscillator ...................................................................................30 8.5full swing crystal oscillator ....................................................................................32 8.6calibrated internal rc oscillator .............................................................................33 8.7external clock .........................................................................................................35
ii 7799d?avr?11/10 atmega8u2/16u2/32u2 8.8clock output buffer .................................................................................................35 8.9system clock prescaler ..........................................................................................35 8.10pll ....................................................................................................................... .36 8.11register description ..............................................................................................37 9 power management and sleep modes ................................................. 42 9.1overview ..................................................................................................................4 2 9.2sleep modes ............................................................................................................42 9.3idle mode .................................................................................................................4 2 9.4power-down mode ...................................................................................................43 9.5power-save mode ....................................................................................................43 9.6standby mode .........................................................................................................43 9.7extended standby mode .........................................................................................43 9.8power reduction register .......................................................................................43 9.9minimizing power consumption ..............................................................................44 9.10register description ..............................................................................................45 10 system control and reset .................................................................... 47 10.1resetting the avr .................................................................................................47 10.2reset sources .......................................................................................................47 10.3internal voltage reference ....................................................................................51 10.4watchdog timer ....................................................................................................51 10.5register description ..............................................................................................55 11 interrupts ................................................................................................ 64 11.1overview ................................................................................................................64 11.2interrupt vectors in atmega8u2/16u2/32u2 ........................................................64 11.3register description ..............................................................................................65 12 i/o-ports .................................................................................................. 67 12.1overview ................................................................................................................67 12.2ports as general digital i/o ...................................................................................68 12.3alternate port functions ........................................................................................72 12.4register description for i/o-ports ..........................................................................82 13 external interrupts ................................................................................. 84 13.1overview ................................................................................................................84 13.2register description ..............................................................................................84 14 timer/counter0 and timer/counter1 prescalers ................................ 88
iii 7799d?avr?11/10 atmega8u2/16u2/32u2 14.1overview ................................................................................................................88 14.2internal clock source ............................................................................................88 14.3prescaler reset .....................................................................................................88 14.4external clock source ...........................................................................................88 14.5register description ..............................................................................................89 15 8-bit timer/counter0 with pwm ............................................................ 91 15.1features ................................................................................................................91 15.2overview ................................................................................................................91 15.3timer/counter clock sources ...............................................................................92 15.4counter unit ..........................................................................................................92 15.5output compare unit .............................................................................................93 15.6compare match output unit ..................................................................................95 15.7modes of operation ...............................................................................................96 15.8timer/counter timing diagrams .........................................................................100 15.9register description ............................................................................................102 16 16-bit timer/counter 1 with pwm ....................................................... 108 16.1features ..............................................................................................................108 16.2overview ..............................................................................................................108 16.3accessing 16-bit registers ..................................................................................110 16.4timer/counter clock sources .............................................................................113 16.5counter unit ........................................................................................................114 16.6input capture unit ...............................................................................................115 16.7output compare units .........................................................................................117 16.8compare match output unit ................................................................................119 16.9modes of operation .............................................................................................120 16.10timer/counter timing diagrams .......................................................................127 16.11register description ..........................................................................................129 17 spi ? serial peripheral interface ......................................................... 138 17.1features ..............................................................................................................138 17.2overview ..............................................................................................................138 17.3 ss pin functionality ............................................................................................142 17.4data modes .........................................................................................................143 17.5register description ............................................................................................145 18 usart ................................................................................................... 148 18.1features ..............................................................................................................148
iv 7799d?avr?11/10 atmega8u2/16u2/32u2 18.2overview ..............................................................................................................148 18.3clock generation .................................................................................................149 18.4frame formats ....................................................................................................152 18.5usart initialization .............................................................................................154 18.6data transmission ? the usart transmitter ....................................................155 18.7data reception ? the usart receiver .............................................................157 18.8asynchronous data reception ............................................................................161 18.9multi-processor communication mode ................................................................164 18.10hardware flow control ......................................................................................165 18.11register description ..........................................................................................167 18.12examples of baud rate setting .........................................................................171 19 usart in spi mode ............................................................................. 176 19.1features ..............................................................................................................176 19.2overview ..............................................................................................................176 19.3clock generation .................................................................................................176 19.4spi data modes and timing ................................................................................177 19.5frame formats ....................................................................................................178 19.6data transfer .......................................................................................................179 19.7register description ............................................................................................181 19.8avr usart mspim vs. avr spi ......................................................................183 20 usb controller ..................................................................................... 185 20.1features ..............................................................................................................185 20.2overview ..............................................................................................................185 20.3usb module powering options ...........................................................................186 20.4general operating modes ...................................................................................189 20.5power modes .......................................................................................................191 20.6memory management ..........................................................................................192 20.7pad suspend .......................................................................................................193 20.8d+/d- read/write .................................................................................................194 20.9usb software operating modes .........................................................................194 20.10registers description ........................................................................................195 21 usb device operating modes ............................................................ 197 21.1overview ..............................................................................................................197 21.2power-on and reset .............................................................................................197 21.3endpoint reset .....................................................................................................197
v 7799d?avr?11/10 atmega8u2/16u2/32u2 21.4usb reset ............................................................................................................198 21.5endpoint selection ...............................................................................................198 21.6endpoint activation ..............................................................................................198 21.7address setup .....................................................................................................199 21.8suspend, wake-up and resume .........................................................................200 21.9detach .................................................................................................................200 21.10remote wake-up ...............................................................................................201 21.11stall request ...................................................................................................201 21.12control endpoint management ....................................................................202 21.13out endpoint management ..............................................................................203 21.14in endpoint management ..................................................................................205 21.15isochronous mode .............................................................................................207 21.16overflow ............................................................................................................207 21.17interrupts ...........................................................................................................208 21.18register description ..........................................................................................209 22 analog comparator .............................................................................. 223 22.1overview ..............................................................................................................223 22.2register description ............................................................................................224 23 boot loader support ? read-while-write self-programming ......... 226 23.1features ..............................................................................................................226 23.2overivew ..............................................................................................................226 23.3application and boot loader flash sections .......................................................226 23.4read-while-write and no read-while-write flash sections ..............................227 23.5boot loader lock bits .........................................................................................229 23.6entering the boot loader program ......................................................................230 23.7addressing the flash during self-programming .................................................232 23.8self-programming the flash ................................................................................233 23.9register description ............................................................................................242 24 debugwire on-chip debug system .................................................. 244 24.1features ..............................................................................................................244 24.2overview ..............................................................................................................244 24.3physical interface ................................................................................................244 24.4software break points .........................................................................................245 24.5limitations of debugwire ...................................................................................245 24.6register description ............................................................................................245
vi 7799d?avr?11/10 atmega8u2/16u2/32u2 25 memory programming ......................................................................... 246 25.1program and data memory lock bits .................................................................246 25.2fuse bits ..............................................................................................................247 25.3signature bytes ...................................................................................................249 25.4calibration byte ...................................................................................................249 25.5page size ............................................................................................................249 25.6parallel programming parameters, pin mapping, and commands .....................250 25.7parallel programming ..........................................................................................252 25.8serial downloading ..............................................................................................259 25.9serial programming pin mapping ........................................................................259 26 electrical characteristics .................................................................... 264 26.1absolute maximum ratings* ...............................................................................264 26.2dc characteristics ...............................................................................................264 26.3speed grades .....................................................................................................266 26.4clock characteristics ...........................................................................................266 26.5system and reset characteristics ......................................................................267 26.6external interrupts characteristics ......................................................................268 26.7spi timing characteristics ..................................................................................269 26.8hardware boot entrancetiming characteristics ..................................................270 26.9parallel programming characteristics .................................................................270 27 typical characteristics ........................................................................ 273 27.1active supply current ..........................................................................................273 27.2idle supply current ..............................................................................................274 27.3power-down supply current ................................................................................275 27.4pin pull-up ...........................................................................................................277 27.5pin driver strength ..............................................................................................278 27.6pin threshold and hysteresis ..............................................................................280 27.7bod threshold ....................................................................................................281 27.8internal oscilllator speed ....................................................................................283 27.9current consumption of peripheral units ............................................................286 27.10current consumption in reset and reset pulsewidth ......................................287 28 register summary ............................................................................... 288 29 instruction set summary ..................................................................... 292 30 ordering information ........................................................................... 294
vii 7799d?avr?11/10 atmega8u2/16u2/32u2 30.1atmega8u2 ........................................................................................................294 30.2atmega16u2 ......................................................................................................295 30.3atmega32u2 ......................................................................................................296 31 packaging information ........................................................................ 297 31.1qfn32 .................................................................................................................297 31.2tqfp32 ...............................................................................................................298 32 errata ..................................................................................................... 299 32.1errata atmega8u2 ..............................................................................................299 32.2errata atmega16u2 ............................................................................................299 32.3errata atmega32u2 ............................................................................................299 33 datasheet revision history ................................................................. 301 33.1rev.7799e ? 09/12 ..............................................................................................301 33.2rev. 7799d ? 11/10 .............................................................................................301 33.3rev. 7799c ? 12/09 .............................................................................................301 33.4rev. 7799b ? 06/09 .............................................................................................301 33.5rev. 7799a ? 03/09 .............................................................................................302 table of contents....................................................................................... i
7799d?avr?11/10 atmel corporation 2325 orchard parkway san jose, ca 95131 usa tel : (+1)(408) 441-0311 fax : (+1)(408) 487-2600 www.atmel.com atmel asia limited unit 1-5 & 16, 19/f bea tower, millennium city 5 418 kwun tong road kwun tong, kowloon hong kong tel : (+852) 2245-6100 fax : (+852) 2722-1369 atmel munich gmbh business campus parkring 4 d-85748 garching b. munich germany tel : (+49) 89-31970-0 fax : (+49) 89-3194621 atmel japan 9f, tonetsu shinkawa bldg. 1-24-8 shinkawa chuo-ku, tokyo 104-0033 japan tel : (+81)(3) 3523-3551 fax : (+81)(3) 3523-7581 ? 2010 atmel corporation. all rights reserved. / rev. corp072610 atmel ? , logo and combinations thereof, and others are registered trademarks or trademarks of atmel corporation or its subsidiaries. other terms and product names may be trademarks of others. disclaimer: the information in this document is provided in connection with atmel products. no license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of atmel products. except as set forth in the atmel terms and conditions of sales located on the atmel website, atmel assumes no liability whatsoever and disclaims any express, implied or statutory warranty relating to its products including, but not limited to, the implied warranty of merchantability, fitness for a particular purpose, or non-infringement. in no event shall atmel be liable for any direct, indirect, consequential, punitive, special or incidental damages (including, without limitation, damages for loss and prof- its, business interruption, or loss of information) arising out of the use or inability to use this document, even if atmel has been advised of the possibility of such damages. atmel makes no representations or warranties with respect to the accuracy or com- pleteness of the contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice. atmel does not make any commitment to update the information contained herein. unless specifically provided otherwise, atmel pr oducts are not suit- able for, and shall not be used in, automotive applications. atmel products are not intended, authorized, or warranted for use as components in applica- tions intended to support or sustain life.


▲Up To Search▲   

 
Price & Availability of TEMICSEMICONDUCTORS-TSC80C51XXX-40CC

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X